133 Commits

Author SHA1 Message Date
hsteller
2585fbc01b versionName "1.5.16" -> versionName "1.5.16_2" 2019-10-12 01:50:12 +00:00
Hendrik Steller
e7e8da5db3 an URL contained one slash too many 2019-10-11 21:34:05 +02:00
Hendrik Steller
44ca33ae0f Version 39 (1.5.16) 2019-10-11 18:19:27 +02:00
Hendrik Steller
a8817babf8 Renamed kvv.imp.fu-berlin.de->mycampus.imp.fu-berlin.de
extracted URL into constant
2019-10-11 18:06:02 +02:00
Caesar2011
7a39a0b854 Version 38 (1.5.15) 2019-02-15 23:12:42 +01:00
Caesar2011
c87241da65 Name in Navigation Header 2019-02-15 23:12:14 +01:00
Caesar2011
6a837d8719 Version 37 reconstructed #2 2019-02-15 18:04:50 +01:00
Caesar2011
8655dc9927 Version 37 reconstructed 2019-02-15 17:56:29 +01:00
Caesar2011
e31d6cd042 Version 36 (1.5.13) 2019-02-11 12:27:42 +01:00
Caesar2011
8f2052180d Lecturer feching delayed #2 2019-02-11 12:26:43 +01:00
Caesar2011
e366e55143 Lecturer feching delayed 2019-02-11 11:16:41 +01:00
Caesar2011
34db5bf901 Event number cache 2019-02-11 00:56:52 +01:00
Caesar2011
ab77ad4974 Logs removed 2019-02-11 00:48:30 +01:00
Caesar2011
d098093c8a HTTP service implemented 2019-02-11 00:20:38 +01:00
Caesar2011
b4e11e3d10 Unbind KVV service 2019-02-10 20:25:44 +01:00
Caesar2011
6048714563 Version 35 (1.5.12) 2019-02-09 01:25:09 +01:00
Caesar2011
30f1cc9a67 Unused imports 2019-02-09 01:23:03 +01:00
Caesar2011
489212c26a KVV as a service to connect SyncAdapter with MainActivity 2019-02-09 01:14:20 +01:00
Caesar2011
28e99f1fa5 More error proof events 2019-02-08 23:44:48 +01:00
Caesar2011
9062035956 cache vvNumber matching 2019-02-08 23:05:57 +01:00
Caesar2011
9769365e19 Cache KVV courses #2 2019-02-08 21:35:00 +01:00
Caesar2011
2441286165 Merge remote-tracking branch 'origin/master' 2019-02-08 20:58:09 +01:00
Sebastian Seedorf
14d5ca6759 Cache KVV courses 2019-02-08 16:29:10 +01:00
Sebastian Seedorf
c7fe1dc3f7 KVV not available implemented 2019-02-08 15:18:10 +01:00
Sebastian Seedorf
72216ea7d6 Load module list and parts only if logged in 2019-02-08 15:17:28 +01:00
Caesar2011
24dcb0e9e0 Version 34 (1.5.11) 2019-02-08 08:56:48 +01:00
Caesar2011
e8c3ca0b0e NumberFormatException 2019-02-08 08:56:19 +01:00
Caesar2011
261878b6e3 Tablet support 2019-02-07 23:36:48 +01:00
Caesar2011
041c46284b NullPointerException and NumberFormatException 2019-02-07 22:47:51 +01:00
Caesar2011
0776447d3b Version 33 (1.5.10) 2019-02-07 22:06:29 +01:00
Caesar2011
a6b5469058 Blackboard "Refresh failed" Fix 2019-02-07 21:53:40 +01:00
Caesar2011
b8be51d6fb Module save fix 2019-02-07 20:36:44 +01:00
Caesar2011
019bdf80ce Schedule fragment for old BB modules cleaned up 2019-02-07 18:47:57 +01:00
Caesar2011
1041144b4f Semester length fix 2019-02-07 18:19:04 +01:00
Caesar2011
5f28f64efc No lecturers fix 2019-02-07 18:15:50 +01:00
Caesar2011
8690aa4a5c App compatibility for Kitkat devices 2019-02-07 00:21:52 +01:00
Caesar2011
9e3fa30366 Version 32 (1.5.9) 2019-02-06 23:54:33 +01:00
Caesar2011
e54a2c8957 Logs removed 2019-02-06 23:54:14 +01:00
Caesar2011
8cdb52417b Fixed sync failure when login not loaded 2019-02-06 23:42:20 +01:00
Caesar2011
40e4612f27 Android Kitkat (19) and below does not support TLS 1.2 2019-02-06 23:25:43 +01:00
Caesar2011
7b85147d74 setNavigationSelection error fixed when ModulePart appended to fragment data 2019-02-06 21:51:29 +01:00
Caesar2011
94ea032389 Blackboard Gradebook (untested) 2019-02-06 20:42:00 +01:00
Caesar2011
94e05ef8ba Added Blackboard Course Cache 2019-02-06 16:08:34 +01:00
Caesar2011
2ec6a3c08d Version 31 (1.5.8) 2019-02-06 12:13:21 +01:00
Caesar2011
123da07d35 Merge remote-tracking branch 'origin/master' 2019-02-06 12:05:32 +01:00
Caesar2011
31850e100d Expandable CardView Empty 2019-02-06 11:37:39 +01:00
Caesar2011
c589889db4 Version 30 (1.5.7) 2019-02-06 09:48:21 +01:00
Caesar2011
8f026f95d8 Sync frequency bug fixed 2019-02-06 09:47:04 +01:00
Caesar2011
c6d9a288a6 Version 29 (1.5.6) 2019-02-06 01:47:21 +01:00
Caesar2011
74e5b16af6 NullPointerException 2019-02-06 01:46:58 +01:00
Caesar2011
8d0f3a83cf Code cleanup 2019-02-06 01:39:05 +01:00
Caesar2011
1414ad8a0e Remove FU cookie on logout 2019-02-06 01:10:30 +01:00
Caesar2011
1d08534f4e Do not sync while login not finished 2019-02-06 00:26:35 +01:00
Caesar2011
e305605583 Lecturer Load Fix 2019-02-05 23:59:09 +01:00
Caesar2011
1e6ef4d6fc Version 28 (1.5.5) 2019-02-05 23:12:37 +01:00
Caesar2011
de9f6a5540 Blackboard event pulling error handling 2019-02-05 23:05:58 +01:00
Caesar2011
25004f8784 Reuse testLoginToken result if set in last 30 secounds 2019-02-05 22:53:42 +01:00
Caesar2011
d78948d349 Login via settings working 2019-02-05 21:07:35 +01:00
Caesar2011
1bbb09499d Module description 2019-02-05 20:21:14 +01:00
Caesar2011
c086a6c6b2 Login code fix 2019-02-05 19:31:59 +01:00
Caesar2011
c9daa8b01b Version 27 (1.5.4) 2019-02-05 17:58:37 +01:00
Caesar2011
91eb7acd72 Lecturer Storage Test 2019-02-05 17:57:21 +01:00
Caesar2011
631bd0dd51 tiny trace log 2019-02-05 17:46:06 +01:00
Caesar2011
c5fc592169 Notification Click Handling #2 2019-02-05 17:41:43 +01:00
Caesar2011
d67542d93a Notification Click Handling 2019-02-05 17:20:57 +01:00
Caesar2011
42f460a2e1 Event Notification Fix 2019-02-05 16:51:42 +01:00
Caesar2011
bde4b0cbd0 Shortcuts on overview fix 2019-02-05 16:36:11 +01:00
Caesar2011
2801261400 Lecturer Storage implemented 2019-02-05 16:35:38 +01:00
Caesar2011
46429d3afe Removed mavenLocal 2019-02-05 15:50:24 +01:00
Sebastian Seedorf
d5d867f4b5 BB Lecturers (not tested) 2019-02-04 17:40:25 +01:00
Caesar2011
f0d090fb8d Better event listing 2019-02-04 02:14:13 +01:00
Caesar2011
a8997a2e99 Grouping events by location 2019-02-04 02:14:13 +01:00
Caesar2011
7ae8a13c9f Fixed double re-login (again) 2019-02-03 23:32:42 +01:00
Caesar2011
a94ce6c755 Notification click implemented 2019-02-03 23:01:44 +01:00
Caesar2011
5bf6573baa Small bug fixes 2019-02-03 21:09:43 +01:00
Caesar2011
0f6a11cf5f Double login fixed 2019-02-03 20:25:01 +01:00
Caesar2011
79f76ccefa Code clean up 2019-02-03 19:56:51 +01:00
Caesar2011
593fb78ef2 Reuse FU identity session 2019-02-03 19:41:40 +01:00
Caesar2011
a6b34f7814 More efficient re-login 2019-02-03 17:11:58 +01:00
Caesar2011
3380e79232 Resource Sync Notification Fix 2019-02-03 16:18:14 +01:00
Caesar2011
d108d430df Version 26 2019-02-01 23:53:12 +01:00
Caesar2011
c7dd46a1a2 Blackboard Resources links 2019-02-01 23:51:35 +01:00
Caesar2011
d5d4b680e8 Merge remote-tracking branch 'origin/master' 2019-02-01 20:41:13 +01:00
Sebastian Seedorf
331c3059bb Notification activity stack fix 2019-02-01 17:43:17 +01:00
Sebastian Seedorf
011e31ac78 Removed unused depencencies 2019-02-01 15:53:07 +01:00
Caesar2011
7f6e794fc8 Blackboard Resources (no links) 2019-02-01 01:50:04 +01:00
Caesar2011
35bb4e1629 Gradebook not available 2019-01-31 21:58:24 +01:00
Caesar2011
48b034b63f More robust blackboard module checking 2019-01-31 21:30:01 +01:00
Caesar2011
ce322bd3ca Login Error Handeling 2019-01-31 20:57:54 +01:00
Caesar2011
c544adbd4b Added KVV projects 2019-01-30 15:12:33 +01:00
Caesar2011
9fe2cf32fd Version 25 2019-01-30 14:42:32 +01:00
Caesar2011
10dc391606 Blackboard Event support 2019-01-30 14:41:05 +01:00
Caesar2011
fac7cb238b Prepare sync if KVV is not supported 2019-01-30 09:49:02 +01:00
Caesar2011
d60ea357d8 Removed Login Error if Blackboard is unavailable 2019-01-30 09:44:24 +01:00
Caesar2011
7c36db2bee Version 24 2019-01-29 18:17:15 +01:00
Caesar2011
c85e510722 Login improved 2019-01-29 18:16:01 +01:00
Caesar2011
740cc192dd Reduced Blackboard Data Usage 2019-01-29 01:46:40 +01:00
Caesar2011
64624ca784 Version 23 2019-01-28 17:40:33 +01:00
Caesar2011
a25b387756 Selectable text (assignment/announcement/news) 2019-01-28 17:39:47 +01:00
Caesar2011
7651eb47e2 Removed unused methods and imports 2019-01-28 17:38:33 +01:00
Caesar2011
86d8078aca "Blackboard never used" check introduced 2019-01-28 17:30:08 +01:00
Caesar2011
068344ff5c Added Blackboard Announcements 2019-01-28 02:21:41 +01:00
Caesar2011
c15fc1339f Added Blackboard Courses to List 2019-01-28 02:03:31 +01:00
Caesar2011
72234d2439 Simplified Login Token 2019-01-27 15:24:12 +01:00
Caesar2011
79305fb5bb Added docs 2019-01-27 15:16:58 +01:00
Joshua
e9ef587821 Merge remote-tracking branch 'origin/master' 2019-01-22 17:08:21 +01:00
Joshua
801b90e489 Modulbeschreibung markierbar 2019-01-22 17:07:55 +01:00
Caesar2011
0610140cf6 Reload If outdated before auto sync 2019-01-17 19:05:31 +01:00
Caesar2011
afcd6afd00 Version 22 2019-01-17 18:48:16 +01:00
Caesar2011
3224946f43 Sync frequency adjustable 2019-01-17 18:46:32 +01:00
Caesar2011
7fe38cd60f Changed event identifier: added type 2019-01-17 17:44:45 +01:00
Caesar2011
31cea12d16 Updated Gradle 2019-01-16 22:44:58 +01:00
Caesar2011
b8fe45e75e Changed event identifier from Id to StartDate 2019-01-16 22:44:35 +01:00
Caesar2011
729d3165f7 Event end time optimized 2019-01-14 14:04:30 +01:00
Caesar2011
6f1705ccf4 Handle register sync properly 2019-01-14 13:53:42 +01:00
Caesar2011
6a56573c6b Version 21 2019-01-14 13:21:32 +01:00
Caesar2011
322cf6f8a5 UnknownFormatException while syncing fixed 2019-01-14 13:19:56 +01:00
Caesar2011
6d30050eae Unused logs and permissions removed 2019-01-14 12:33:34 +01:00
Caesar2011
45a5513b54 Version 20 2019-01-09 15:52:51 +01:00
Caesar2011
e98e9f5e2f Merge branch 'kvvservice2' 2019-01-09 15:52:28 +01:00
Caesar2011
7d803777f8 Notifications added 2019-01-09 15:52:09 +01:00
Caesar2011
7cc0709133 New KVV login working 2019-01-09 14:58:08 +01:00
Caesar2011
21d247052d New KVV login preparation (works only via VPN or internal) 2019-01-09 01:22:13 +01:00
Caesar2011
57853eccf1 Sync notifications for announcements 2019-01-07 23:34:48 +01:00
Caesar2011
ceccd77f18 Periodic sync, reload from memory if outdated 2019-01-07 21:14:59 +01:00
Caesar2011
ae53e94108 Periodic sync, reload from memory if outdated 2019-01-07 14:59:48 +01:00
Caesar2011
786c001bbd unfinished code 2019-01-07 13:28:59 +01:00
Caesar2011
d4275aad90 Version 19 2018-12-19 15:58:12 +01:00
Caesar2011
f9fb7e8351 Merge branch 'kvvservice' 2018-12-19 15:55:39 +01:00
Caesar2011
889007ab42 Version 18 2018-12-18 15:50:54 +01:00
Joshua
c549bb39a4 fehler bei anzeigen von Ordnern mit umlauten behoben 2018-12-17 16:06:41 +01:00
Caesar2011
1e0b2a8952 Version 17 2018-12-06 13:38:26 +01:00
Joshua
54196f3794 Projekt Fehler behoben 2018-12-04 16:43:32 +01:00
98 changed files with 4180 additions and 1236 deletions

View File

@@ -7,8 +7,8 @@ android {
applicationId "de.sebse.fuplanner"
minSdkVersion 15
targetSdkVersion 28
versionCode 16
versionName "1.3.5"
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
}

View File

@@ -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());
}
}

View File

@@ -18,8 +18,6 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
@@ -33,7 +31,9 @@
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" />
@@ -80,6 +80,20 @@
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>

View File

@@ -1,8 +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;
@@ -14,12 +21,15 @@ 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;
@@ -39,13 +49,17 @@ import de.sebse.fuplanner.fragments.moddetails.ModDetailFragment;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.CanteenListener;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
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.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.CustomNotificationManager;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.Preferences;
@@ -60,27 +74,58 @@ public class MainActivity extends AppCompatActivity
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_SCHEDULE = 4;
private static final int FRAGMENT_CANTEENS = 5;
private static final int FRAGMENT_CANTEENS_DETAILS = 6;
private static final int FRAGMENT_PREFERENCES = 7;
private static final int FRAGMENT_NEWS = 8;
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 KVV mKVV;
private NewsManager mNewsManager;
private CanteenBrowser mCanteenBrowser;
private final Logger log = new Logger(this);
private NavigationView mNavigationView;
private boolean mAlreadyCreated = false;
// KVV service
private ArrayList<KVVCallback> mCallbacks = new ArrayList<>();
@Nullable private KVV mKVV;
boolean mBound = false;
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
KVV.LocalBinder binder = (KVV.LocalBinder) service;
mKVV = binder.getService();
mKVV.addListener("mainactivity", MainActivity.this);
for (KVVCallback callback : mCallbacks) {
callback.get(mKVV);
}
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mKVV.removeListener("mainactivity");
mBound = false;
mKVV = null;
}
};
private int mFragmentPage = FRAGMENT_NONE;
@NotNull
private String mFragmentData = "";
@@ -90,14 +135,24 @@ public class MainActivity extends AppCompatActivity
private CustomAccountManager mAccountManager;
private boolean isPaused = false;
private boolean isLoggedInBeforePause = false;
private boolean isDrawerFixed = false;
private Function<Modules, Void> mMolduleListUpdateFunction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAccountManager = new CustomAccountManager(AccountManager.get(this), () -> MainActivity.this);
isDrawerFixed = getResources().getBoolean(R.bool.isDrawerFixed);
int desiredPage = getDefaultFragmentAfterLogin();
String desiredData = "";
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);
}
@@ -106,11 +161,13 @@ public class MainActivity extends AppCompatActivity
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
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);
@@ -120,7 +177,7 @@ public class MainActivity extends AppCompatActivity
if (!mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
desiredPage = getDefaultFragmentAfterLogout();
desiredData = "";
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
updateNavigation();
changeFragment(desiredPage, desiredData);
} else {
@@ -128,35 +185,95 @@ public class MainActivity extends AppCompatActivity
changeFragment(FRAGMENT_STARTUP);
int targetPage = desiredPage;
String targetData = desiredData;
getKVV().account().restoreOnlineLogin(isRestored -> {
updateNavigation();
if (isRestored)
changeFragment(targetPage, targetData);
else
changeFragment(getDefaultFragmentAfterLogout());
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;
isLoggedInBeforePause = getKVV().account().isLoggedIn();
getKVV(kvv -> isLoggedInBeforePause = kvv.account().isLoggedIn());
}
@Override
protected void onResume() {
super.onResume();
if (isPaused) {
getKVV().account().restoreOnlineLogin(isRestored -> {
updateNavigation();
if (isRestored && !isLoggedInBeforePause)
changeFragment(getDefaultFragmentAfterLogin());
else if (!isRestored && isLoggedInBeforePause) {
getKVV().account().logout(false);
changeFragment(getDefaultFragmentAfterLogout());
}
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;
@@ -170,30 +287,32 @@ public class MainActivity extends AppCompatActivity
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
drawer.closeDrawer(GravityCompat.START);
} else {
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);
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 {
changeFragment(FRAGMENT_MODULES);
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
showToast(R.string.back_to_exit);
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD);
}
} else if (mFragmentPage == FRAGMENT_CANTEENS_DETAILS) {
DaySwitcherFragment fragment = (DaySwitcherFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS_DETAILS));
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
fragment.gotoFragmentPart(0);
} else {
changeFragment(FRAGMENT_CANTEENS);
}
} else if (getKVV().account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
changeFragment(getDefaultFragmentAfterLogin());
} else {
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
showToast(R.string.back_to_exit);
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV);
}
});
}
}
@@ -260,13 +379,17 @@ public class MainActivity extends AppCompatActivity
startActivity(sendIntent);
break;
case R.id.nav_logout:
getKVV().account().logout(true);
getKVV().modules().list().delete();
getKVV(kvv -> {
kvv.account().logout(true);
kvv.modules().list().delete();
});
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
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++) {
@@ -311,11 +434,12 @@ public class MainActivity extends AppCompatActivity
return this.mNewsManager;
}
public KVV getKVV() {
public void getKVV(KVVCallback callback) {
if (this.mKVV == null) {
this.mKVV = new KVV(this, this);
mCallbacks.add(callback);
} else {
callback.get(this.mKVV);
}
return this.mKVV;
}
public CanteenBrowser getCanteenBrowser() {
@@ -337,7 +461,7 @@ public class MainActivity extends AppCompatActivity
setRefreshFailedBanner(false);
updateNavigation();
changeFragment(getDefaultFragmentAfterLogout());
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
//mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
}
private void toLoginState(String fullName, String email, int newFragment) {
@@ -350,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, "");
}
@@ -371,9 +508,6 @@ 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;
@@ -422,20 +556,27 @@ public class MainActivity extends AppCompatActivity
private void setNavigationSelection() {
MenuItem item = null;
int dotPos = mFragmentData.indexOf(".");
String moduleId = mFragmentData;
if (dotPos != -1)
moduleId = moduleId.substring(0, dotPos);
switch (mFragmentPage) {
case FRAGMENT_MODULES_DETAILS:
getKVV().modules().list().find(mFragmentData, success -> {
int size = mNavigationView.getMenu().size();
//noinspection ConstantConditions
String title = success == null ? null : success.title;
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
String finalModuleId = moduleId;
getKVV(kvv -> {
kvv.modules().list().find(finalModuleId, success -> {
int size = mNavigationView.getMenu().size();
//noinspection ConstantConditions
String title = success == null ? null : success.title;
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
}
}
}
}, log::e);
}, log::e);
});
return;
case FRAGMENT_MODULES:
item = mNavigationView.getMenu().findItem(R.id.nav_modules);
@@ -446,15 +587,19 @@ public class MainActivity extends AppCompatActivity
case FRAGMENT_CANTEENS_DETAILS:
getCanteenBrowser().getCanteens(success -> {
int size = mNavigationView.getMenu().size();
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
//noinspection ConstantConditions
String title = canteen == null ? null : canteen.getName();
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
try {
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
//noinspection ConstantConditions
String title = canteen == null ? null : canteen.getName();
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}, log::e);
return;
@@ -486,10 +631,10 @@ 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);
}
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
});
}
@@ -497,21 +642,23 @@ public class MainActivity extends AppCompatActivity
int MAX_COUNT = isLoggedIn ? 3 : 2;
final int[] count = {0};
if (isLoggedIn) {
getKVV().modules().list().recv(success -> {
int i = 0;
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
Modules.Module module = it.next();
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
menuItem.setOnMenuItemClickListener(item -> {
onModulesFragmentInteraction(module.getID());
return false;
});
i++;
}
if (++count[0] == MAX_COUNT) done.run();
}, error -> {
if (++count[0] == MAX_COUNT) done.run();
log.e(error);
getKVV(kvv -> {
kvv.modules().list().recv(success -> {
int i = 0;
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
Modules.Module module = it.next();
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
menuItem.setOnMenuItemClickListener(item -> {
onModulesFragmentInteraction(module.getID());
return false;
});
i++;
}
if (++count[0] == MAX_COUNT) done.run();
}, error -> {
if (++count[0] == MAX_COUNT) done.run();
log.e(error);
});
});
}
getCanteenBrowser().getCanteens(success -> {
@@ -552,16 +699,18 @@ public class MainActivity extends AppCompatActivity
private void updateNavigation() {
mQueue.add(() -> {
boolean isLoggedIn = getKVV().account().isLoggedIn();
setNavigationHeader(isLoggedIn);
mNavigationView.getMenu().clear();
if (isLoggedIn)
mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
else
mNavigationView.inflateMenu(R.menu.activity_main_drawer);
afterAnyMenuInflate(isLoggedIn, () -> {
setNavigationSelection();
mQueue.next();
getKVV(kvv -> {
boolean isLoggedIn = kvv.account().isLoggedIn();
setNavigationHeader(isLoggedIn);
mNavigationView.getMenu().clear();
if (isLoggedIn)
mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
else
mNavigationView.inflateMenu(R.menu.activity_main_drawer);
afterAnyMenuInflate(isLoggedIn, () -> {
setNavigationSelection();
mQueue.next();
});
});
});
}
@@ -583,6 +732,11 @@ public class MainActivity extends AppCompatActivity
setNavigationSelection();
}
@Override
public void onModulesFragmentListUpdate(Function<Modules, Void> update) {
this.mMolduleListUpdateFunction = update;
}
@Override
public void onCanteensFragmentInteraction(final int itemID) {
changeFragment(FRAGMENT_CANTEENS_DETAILS, String.valueOf(itemID));
@@ -635,8 +789,21 @@ public class MainActivity extends AppCompatActivity
@Override
public void onLogin(LoginToken token) {
toLoginState(token.getFullName(), token.getEmail(), getDefaultFragmentAfterLogin());
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
@@ -658,4 +825,15 @@ public class MainActivity extends AppCompatActivity
public CustomAccountManager getAccountManager() {
return mAccountManager;
}
public interface KVVCallback {
void get(KVV kvv);
}
@Override
public void onModuleListPartiallyUpdated(Modules modules) {
if (mMolduleListUpdateFunction != null) {
mMolduleListUpdateFunction.apply(modules);
}
}
}

View File

@@ -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());

View File

@@ -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;
@@ -66,15 +68,15 @@ public class ModulesFragment extends Fragment {
private void refresh(boolean forceRefresh) {
if (mMainActivityListener != null) {
mMainActivityListener.getKVV().modules().list().recv(success -> {
adapter.setModules(success);
//if (mMainActivityListener != null)
// mMainActivityListener.refreshNavigation();
swipeLayout.setRefreshing(false);
}, error -> {
log.e(error.toString());
swipeLayout.setRefreshing(false);
}, forceRefresh);
mMainActivityListener.getKVV(kvv -> {
kvv.modules().list().recv(success -> {
adapter.setModules(success);
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);
}
}

View File

@@ -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)));
}
}
}
}
}

View File

@@ -18,8 +18,9 @@ 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.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;
@@ -63,21 +64,25 @@ public class ScheduleFragment extends Fragment implements
public void invalidate(boolean forceRefresh) {
if (mListener == null) return;
mListener.getKVV().modules().list().recv(modules -> {
mModules = modules;
final int[] i = {0};
for (Modules.Module module: mModules) {
mListener.getKVV().modules().events().recv(module, success1 -> {
i[0]++;
if (i[0] >= mModules.size()) {
if (mWeekView != null) {
mWeekView.invalidate();
mWeekView.notifyDatasetChanged();
mListener.getKVV(kvv -> {
kvv.modules().list().recv(modules -> {
mModules = modules;
final int[] i = {0};
Iterator<Modules.Module> iter = mModules.latestSemesterIterator();
while (iter.hasNext()) {
Modules.Module module = iter.next();
kvv.modules().events().recv(module, success1 -> {
i[0]++;
if (i[0] >= mModules.size()) {
if (mWeekView != null) {
mWeekView.invalidate();
mWeekView.notifyDatasetChanged();
}
}
}
}, log::e, forceRefresh);
}
}, log::e, forceRefresh);
}, log::e, forceRefresh);
}
}, log::e, forceRefresh);
});
}
@Override
@@ -119,7 +124,11 @@ public class ScheduleFragment extends Fragment implements
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
ArrayList<WeekViewEvent> events = new ArrayList<>();
if (mModules != null){
Semester latestSemester = mModules.getLatestSemester();
for (Modules.Module mod: mModules) {
if (mod.getModuleType() == Modules.TYPE_BB && mod.semester != null && !mod.semester.equals(latestSemester)) {
continue;
}
if (mod.events != null) {
Iterator<Event> it_modEvents = mod.events.getEventsOfMonth(newYear, newMonth);
while (it_modEvents.hasNext()) {
@@ -180,20 +189,22 @@ public class ScheduleFragment extends Fragment implements
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
if (mListener == null) return;
mListener.getKVV().modules().list().find(moduleId, module -> {
String moduleName = module.title;
alertDialogBuilder
.setTitle(event.getName())
.setMessage(
getResources().getString(R.string.module_name, moduleName) + "\n" +
getResources().getString(R.string.location_name, event.getLocation()) + "\n" +
getResources().getString(R.string.date_scale, UtilsDate.getModifiedTime(getContext(), event.getStartTime().getTimeInMillis()), UtilsDate.getModifiedTime(getContext(), event.getEndTime().getTimeInMillis()+1))
)
.setCancelable(true)
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
mListener.getKVV(kvv -> {
kvv.modules().list().find(moduleId, module -> {
String moduleName = module.title;
alertDialogBuilder
.setTitle(event.getName())
.setMessage(
getResources().getString(R.string.module_name, moduleName) + "\n" +
getResources().getString(R.string.location_name, event.getLocation()) + "\n" +
getResources().getString(R.string.date_scale, UtilsDate.getModifiedTime(getContext(), event.getStartTime().getTimeInMillis()), UtilsDate.getModifiedTime(getContext(), event.getEndTime().getTimeInMillis()+1))
)
.setCancelable(true)
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}, log::e);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}, log::e);
});
}
}

View File

@@ -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);

View File

@@ -21,14 +21,12 @@ import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.AnnouncementViewHolder;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
class ModDetailAnnounceAdapter extends RecyclerView.Adapter<CustomViewHolder> {
@Nullable private Modules.Module mModule = null;
private Logger log = new Logger(this);
@NonNull private final Download.OnDownloadRequestInterface requestInterface;
ModDetailAnnounceAdapter(@NonNull Download.OnDownloadRequestInterface requestInterface) {

View File

@@ -82,27 +82,31 @@ public class ModDetailAnnounceFragment extends Fragment implements Download.OnDo
}
private void refresh(boolean forceRefresh) {
if (mListener == null)
return;
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
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) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Announcement";
getDownload().openDownloadDialog(title, url, folderName);
}, log::e);
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

View File

@@ -21,14 +21,12 @@ import de.sebse.fuplanner.services.kvv.types.Assignment;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.AnnouncementViewHolder;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
class ModDetailAssignmentAdapter extends RecyclerView.Adapter<CustomViewHolder> {
@Nullable private Modules.Module mModule = null;
private Logger log = new Logger(this);
@NonNull private final Download.OnDownloadRequestInterface requestInterface;
ModDetailAssignmentAdapter(@NonNull Download.OnDownloadRequestInterface requestInterface) {

View File

@@ -82,27 +82,31 @@ public class ModDetailAssignmentFragment extends Fragment implements Download.On
}
private void refresh(boolean forceRefresh) {
if (mListener == null)
return;
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
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) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Assignment";
getDownload().openDownloadDialog(title, url, folderName);
}, log::e);
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

View File

@@ -1,7 +1,9 @@
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;
@@ -19,7 +21,6 @@ import de.sebse.fuplanner.services.kvv.types.EventList;
import de.sebse.fuplanner.services.kvv.types.GroupedEvents;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
import de.sebse.fuplanner.tools.ui.StringViewHolder;
@@ -41,8 +42,6 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private Modules.Module mValue;
private final ArrayList<Pair<Integer, Object>> mPositionalData;
private final Logger log = new Logger(this);
ModDetailEventAdapter() {
mValue = null;
mPositionalData = new ArrayList<>();
@@ -81,19 +80,20 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
for (Map.Entry<String, GroupedEvents> value: listsGrouped.entrySet()) {
if (value.getValue().getGroups().size() > 0) {
mPositionalData.add(new Pair<>(TYPE_HEADER, value.getKey()));
boolean showAsGrouped = true;
for (GroupedEvents.Group group : value.getValue().getGroups()) {
if (group.getSkippedDates().size() > 2) {
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;
break;
}
if (showAsGrouped) {
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
} else {
ungroupedGroups.add(group);
}
}
if (showAsGrouped) {
for (GroupedEvents.Group group : value.getValue().getGroups()) {
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
}
} else {
for (Event event : value.getValue()) {
for (GroupedEvents.Group ungroupedGroup : ungroupedGroups) {
for (Event event: ungroupedGroup) {
mPositionalData.add(new Pair<>(TYPE_UNGROUPED, event));
}
}
@@ -178,7 +178,7 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
end = UtilsDate.getModifiedDate(lastDateTime);
weekday = UtilsDate.getModifiedDate(context, firstDateTime, "E");
startTime = UtilsDate.getModifiedTime(context, firstDateTime);
endTime = UtilsDate.getModifiedTime(context, lastDateTime);
endTime = UtilsDate.getModifiedTime(context, lastDateTime+1);
for (long skippedDate : group.getSkippedDates()) {
if (excepts == null) {
excepts = new StringBuilder(UtilsDate.getModifiedDate(skippedDate));
@@ -186,9 +186,30 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
excepts.append(", ").append(UtilsDate.getModifiedDate(skippedDate));
}
}
ig.mTitle.setText(context.getString(R.string.event_scale, weekday, startTime, endTime));
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;
@@ -199,13 +220,29 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
else
start = UtilsDate.getModifiedDateTime(context, event.getStartDate());
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
end = UtilsDate.getModifiedTime(context, event.getEndDate());
end = UtilsDate.getModifiedTime(context, event.getEndDate()+1);
else
end = UtilsDate.getModifiedDateTime(context, event.getEndDate());
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("");
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();
});
}
}

View File

@@ -81,16 +81,18 @@ public class ModDetailEventFragment extends Fragment {
}
private void refresh(boolean forceRefresh) {
if (mListener == null)
return;
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
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

View File

@@ -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 -> {
Modules.Module module = success.get(mItemPos);
if (mListener != null && module != null)
mListener.onTitleTextChange(module.title);
}, log::e);
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);
});
}
}

View File

@@ -81,16 +81,18 @@ public class ModDetailGradebookFragment extends Fragment {
}
private void refresh(boolean forceRefresh) {
if (mListener == null)
return;
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
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

View File

@@ -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;
@@ -21,7 +22,6 @@ import de.sebse.fuplanner.services.kvv.types.Event;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
import de.sebse.fuplanner.tools.ui.MailViewHolder;
@@ -37,12 +37,12 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private static final int TYPE_SHOW_MORE = 3;
private static final int TYPE_MAIL = 4;
private static final int TYPE_SHORTCUTS = 5;
private static final int TYPE_NO_ITEMS = 6;
@Nullable private final ModDetailListener mListener;
private Modules.Module mValue;
private final ArrayList<Pair<Integer, Object>> mPositionalData;
private Logger log = new Logger(this);
ModDetailOverviewAdapter(@Nullable final ModDetailListener listener) {
mValue = null;
@@ -57,8 +57,10 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private void setModule() {
mPositionalData.clear();
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.DESCRIPTION));
mPositionalData.add(new Pair<>(TYPE_DESCRIPTION, null));
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++) {
@@ -79,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
@@ -102,6 +107,10 @@ 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);
@@ -193,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
));
@@ -236,6 +245,7 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
});
break;
case TYPE_SHOW_MORE:
case TYPE_NO_ITEMS:
CustomViewHolder c = (CustomViewHolder) holder;
c.mView.setOnClickListener(view -> {
if (mListener != null) mListener.gotoFragmentPart((Integer) data.second, -1);

View File

@@ -86,14 +86,16 @@ public class ModDetailOverviewFragment extends Fragment {
private void refresh(boolean forceRefresh) {
if (mListener != null) {
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
mListener.getKVV(kvv -> {
kvv.modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
log.e(error);
}, forceRefresh);
});
}
}

View File

@@ -24,6 +24,7 @@ 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) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
Resource.File file = (Resource.File) node.getContent();
getDownload().openDownloadDialog(file, folderName);
}, log::e);
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,16 +154,18 @@ public class ModDetailResourceFragment extends Fragment {
}
private void refresh(boolean forceRefresh) {
if (mListener == null)
return;
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
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);
});
}
}
private Download getDownload() {

View File

@@ -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};

View File

@@ -1,6 +1,7 @@
package de.sebse.fuplanner.services.canteen;
import android.content.Context;
import android.os.Build;
import org.json.JSONArray;
import org.json.JSONException;
@@ -64,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) {
@@ -125,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) {
@@ -172,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) {

View File

@@ -28,6 +28,14 @@ public class FUAuthenticator extends AbstractAccountAuthenticator {
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
final AccountManager am = AccountManager.get(mContext);
if (am.getAccountsByType(accountType).length > 0) {
final Bundle bundle = new Bundle();
bundle.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION);
bundle.putString(AccountManager.KEY_ERROR_MESSAGE, "Already an account added!");
return bundle;
}
final Intent intent = new Intent(mContext, FUAuthenticatorActivity.class);
intent.putExtra(FUAuthenticatorActivity.ARG_ACCOUNT_TYPE, accountType);
intent.putExtra(FUAuthenticatorActivity.ARG_AUTH_TYPE, authTokenType);
@@ -58,6 +66,13 @@ public class FUAuthenticator extends AbstractAccountAuthenticator {
if (password != null) {
try {
authToken = new UserLoginTask(account.name, password, authTokenType, mContext).execute((Void) null).get();
// Login when auth/re-auth
if (!TextUtils.isEmpty(authToken) && authToken.startsWith("Error: ")) {
// if password is not wrong -> Networking error
if (!authToken.contains("100343"))
throw new NetworkErrorException(authToken);
else authToken = null;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {

View File

@@ -6,25 +6,19 @@ import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.material.textfield.TextInputEditText;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.R;
import static de.sebse.fuplanner.services.fulogin.UserLoginTask.PARAM_USER_PASS;
@@ -32,21 +26,16 @@ 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 implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
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 EditText mEmailView;
EditText mPasswordView;
private TextInputEditText mEmailView;
TextInputEditText mPasswordView;
TextView mErrorView;
private View mProgressView;
private View mLoginFormView;
@@ -66,12 +55,13 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity implem
mAccountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);
mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
mAuthTokenType = mAuthTokenType != null ? mAuthTokenType : AccountGeneral.AUTHTOKEN_TYPE_KVV;
mIsAddingNewAccount = getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false);
setContentView(R.layout.activity_fu_authenticator);
mErrorView = findViewById(R.id.error_textview);
// Set up the login form.
mEmailView = findViewById(R.id.input_username);
populateAutoComplete();
mPasswordView = findViewById(R.id.input_password);
mPasswordView.setOnEditorActionListener((textView, id, keyEvent) -> {
@@ -89,49 +79,6 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity implem
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
/*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}*/
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
@@ -218,43 +165,6 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity implem
});
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
void finishLogin(Intent intent) {
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);

View File

@@ -14,9 +14,13 @@ import java.util.concurrent.atomic.AtomicReference;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.services.kvv.sync.Login;
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;
/**
@@ -34,20 +38,23 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
};*/
static final String PARAM_USER_PASS = "PARAM_USER_PASS";
private final String mEmail;
private final String mUsername;
private final String mPassword;
private final Login mVolleyLogin;
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 email, String password, String tokenType, @NotNull Context context) {
mEmail = email;
UserLoginTask(String username, String password, @NotNull String tokenType, @NotNull Context context) {
mUsername = username;
mPassword = password;
mTokenType = tokenType;
mVolleyLogin = new Login(context);
FULogin mFULogin = new FULogin(context);
mKVVLogin = new KVVLogin(context, mFULogin);
mBBLogin = new BBLogin(context, mFULogin);
if (context instanceof FUAuthenticatorActivity)
mActivity = (FUAuthenticatorActivity) context;
}
@@ -57,37 +64,59 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
// TODO: attempt authentication against a network service.
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<LoginToken> login = new AtomicReference<>();
mVolleyLogin.doLogin(mEmail, mPassword, success -> {
mVolleyLogin.testLoginToken(success, success1 -> {
login.set(success);
latch.countDown();
}, error -> latch.countDown());
}, error -> latch.countDown());
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();
}
log.d(login.get());
if (login.get() == null) {
return null;
} else {
return login.get().toJsonString();
}
/*for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword) ? "auth token here" : null;
}
}
// TODO: register the new account here.
return null;*/
return login.get();
}
@Override
@@ -99,16 +128,20 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
mActivity.mAuthTask = null;
mActivity.showProgress(false);
if (success != null) {
if (success != null && !success.startsWith("Error: ")) {
final Intent res = new Intent();
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mEmail);
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 {
} 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);
}
}

View File

@@ -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/";
}

View File

@@ -1,31 +1,104 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
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;
public class KVV {
private final HashMap<String, Object> addons = new HashMap<>();
private final KVVListener mListener;
private final Context mContext;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.tools.CustomAccountManager;
public KVV(KVVListener listener, Context context) {
this.mListener = listener;
this.mContext = context;
}
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, mContext));
return (Login) addAndGet("account", () -> new Login(mListener, getApplicationContext()));
}
@NotNull
public Modules modules() {
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, mContext));
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;
}
}

View File

@@ -2,16 +2,20 @@ package de.sebse.fuplanner.services.kvv;
import com.android.volley.NetworkResponse;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
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(LoginToken token) {}
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();

View File

@@ -1,59 +1,89 @@
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.services.kvv.types.LoginToken;
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 LoginToken mToken;
@Nullable private LoginTokenKVV mTokenKVV;
@Nullable private LoginTokenBB mTokenBB;
private boolean mLoginPending = false;
private final NetworkCallbackCollector<LoginToken> mRefreshCallbacks = new NetworkCallbackCollector<>();
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(BooleanInterface callback) {
public void restoreOnlineLogin(IntegerInterface callback) {
mRestoreCallbacks.add(new Pair<>(callback::run, null));
if (mLoginPending) {
callback.run(false);
return;
}
mLoginPending = true;
LoginToken.load(mListener.getAccountManager(), token -> {
boolean result = setToken(token);
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;
log.d("loginToken", token != null ? token.toString() : null);
callback.run(result);
mRestoreCallbacks.responseResponse(RESTORE_STATUS_ERROR);
});
}
public void isOfflineStoredAvailable(BooleanInterface callback) {
LoginToken.load(mListener.getAccountManager(), token -> {
callback.run(token != null);
});
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 (mToken == null)
if (mTokenKVV == null || mTokenBB == null)
return true;
if (delete)
mToken.delete(mListener.getAccountManager());
mToken = null;
return handleCallbacks();
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() {
@@ -61,52 +91,81 @@ public class Login extends HTTPService {
}
public boolean isLoggedIn() {
return mToken != null;
return mTokenKVV != null && mTokenBB != null;
}
public boolean isInOnlineMode() {
return isLoggedIn();
}
void testLoginToken(@NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
if (mToken == null) {
void testLoginToken(@NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
if (mTokenKVV == null) {
errorCallback.onError(new NetworkError(100173, -1, "Not logged in!"));
return;
}
testLoginToken(mToken, callback, errorCallback);
if (mTokenBB == null) {
errorCallback.onError(new NetworkError(100174, -1, "Not logged in!"));
return;
}
testLoginToken(mTokenKVV, mTokenBB, callback, errorCallback);
}
private void testLoginToken(@NotNull LoginToken token, @NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
new de.sebse.fuplanner.services.kvv.sync.Login(getContext()).testLoginToken(token, callback, errorCallback);
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 LoginToken getLoginToken() {
return mToken;
@Nullable public LoginTokenKVV getLoginTokenKVV() {
return mTokenKVV;
}
void refreshLogin(NetworkCallback<LoginToken> success, NetworkErrorCallback error) {
@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();
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, ignored -> {
restoreOnlineLogin(isRestored -> {
if (isRestored)
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 {
else if (restoreResult == RESTORE_STATUS_INVALID_PASSWORD) {
logout(true);
mRefreshCallbacks.responseError(new NetworkError(100180, 403, "Re-login failed!"));
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() {
if (mToken != null) {
mListener.onLogin(mToken);
private boolean handleCallbacks(boolean isOnlyRefresh) {
if (mTokenKVV != null || mTokenBB != null) {
mListener.onLogin(mTokenKVV, mTokenBB, isOnlyRefresh);
return true;
} else {
mListener.onLogout();
@@ -114,15 +173,20 @@ public class Login extends HTTPService {
}
}
private boolean setToken(@Nullable LoginToken token) {
if (token == null)
private boolean setToken(@Nullable LoginTokenKVV tokenKVV, @Nullable LoginTokenBB tokenBB) {
if (tokenKVV == null || tokenBB == null)
return false;
boolean isOnlyRefresh = mToken != null;
mToken = token;
return isOnlyRefresh || handleCallbacks();
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);
}
}

View File

@@ -2,6 +2,8 @@ package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import com.android.volley.NetworkResponse;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
@@ -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);
}

View File

@@ -10,6 +10,7 @@ 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;
@@ -33,12 +34,12 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
}
@Override
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
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("https://kvv.imp.fu-berlin.de/direct/announcement/site/%s.json?n=999999&d=999999999", ID), mLogin.getLoginToken().getCookies(), response -> {
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!"));
@@ -81,11 +82,59 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
}
}
// Empty announcements *may be* because token is invalid -> check
if (announcements.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(announcements), errorCallback);
else
callback.onResponse(announcements);
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!"));
});
}
}

View File

@@ -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);
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());
}
}

View File

@@ -1,20 +1,30 @@
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);
}
@@ -32,12 +42,12 @@ public class ModulesEvents extends PartModules<EventList> {
}
@Override
protected void upgrade(final String ID, final NetworkCallback<EventList> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
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("https://kvv.imp.fu-berlin.de/direct/calendar/site/%s.json?detailed=true", ID), mLogin.getLoginToken().getCookies(), response -> {
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!"));
@@ -73,11 +83,106 @@ public class ModulesEvents extends PartModules<EventList> {
}
}
// Empty events *may be* because token is invalid -> check
if (events.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(events), errorCallback);
else
callback.onResponse(events);
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;
}
}

View File

@@ -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!")));
}
}

View File

@@ -33,12 +33,12 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
}
@Override
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Grade>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
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("https://kvv.imp.fu-berlin.de/direct/gradebook/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
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!"));
@@ -71,6 +71,85 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
}
}
callback.onResponse(gradebook);
}, error -> errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get 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!"));
});
}
}

View File

@@ -12,7 +12,11 @@ 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;
@@ -29,7 +33,10 @@ 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);
@@ -46,14 +53,28 @@ public class ModulesList extends HTTPService {
return null;
}
public void reloadIfOutdated() {
try {
if (mModules != null && mModules.isNewerVersionInStorage(getContext())) {
restore();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void find(String moduleID, NetworkCallback<Modules.Module> moduleNetworkCallback, NetworkErrorCallback errorCallback) {
find(moduleID, moduleNetworkCallback, errorCallback, RETRY_COUNT);
}
private void find(String moduleID, NetworkCallback<Modules.Module> moduleNetworkCallback, NetworkErrorCallback errorCallback, int retries) {
if (mModules != null && mLogin.getLoginToken() != null && mLogin.getLoginToken().isOtherUser(mModules.getUsername()))
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;
}
@@ -86,6 +107,9 @@ public class ModulesList extends HTTPService {
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (this.mModules == null) {
recv(success -> {}, log::e);
}
}
public void delete() {
@@ -104,101 +128,330 @@ public class ModulesList extends HTTPService {
}
private void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh, final int retries) {
if (mModules != null && mLogin.getLoginToken() != null && mLogin.getLoginToken().isOtherUser(mModules.getUsername()))
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;
}
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 -> {
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);
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 upgrade(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
log.d(mLogin.isInOnlineMode(), mLogin.getLoginToken());
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101105, 500, "Currently running in offline mode!"));
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;
}
get("https://kvv.imp.fu-berlin.de/direct/site.json", mLogin.getLoginToken().getCookies(), response -> {
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(101101, 403, "No module list retrieved!"));
errorCallback.onError(new NetworkError(101111, 403, "No membership list retrieved!"));
return;
}
Modules modules = new Modules(mLogin.getLoginToken().getUsername());
JSONArray sites;
JSONArray memberships;
try {
JSONObject json = new JSONObject(body);
sites = json.getJSONArray("site_collection");
memberships = json.getJSONArray("membership_collection");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101102, 403, "Cannot parse module list!"));
errorCallback.onError(new NetworkError(101112, 403, "Cannot parse membership list!"));
return;
}
for (int i = 0; i < sites.length(); i++) {
final int[] latch = {memberships.length()};
if (latch[0] == 0) {
successCallback.onResponse(modules);
return;
}
for (int i = 0; i < memberships.length(); i++) {
try {
JSONObject site = sites.getJSONObject(i);
String semester_string = site.getJSONObject("props").optString("term_eid", null);
if (semester_string == null)
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;
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);
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(new NetworkError(101103, 403, "Cannot parse module list!"));
log.e("ID:", i, "JSON:", sites);
log.e("ID:", i, "JSON:", memberships);
e.printStackTrace();
errorCallback.onError(new NetworkError(101117, 403, "Cannot parse membership list!"));
return;
} catch (NoSuchFieldException e) {
log.e(new NetworkError(101106, 403, "Cannot parse module list!"));
log.e("ID:", i, "JSON:", sites);
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();
}
}
// 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!")));
}, 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;
}
}

View File

@@ -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!")));
}
}

View File

@@ -1,6 +1,7 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import org.json.JSONArray;
@@ -9,6 +10,9 @@ 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;
@@ -38,12 +42,12 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
}
@Override
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Resource>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
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("https://kvv.imp.fu-berlin.de/direct/content/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
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!"));
@@ -95,23 +99,141 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
} 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);
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();
}
}
}
}
}
// Empty resources *may be* because token is invalid -> check
if (resources.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(root), errorCallback);
else
callback.onResponse(root);
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<>());
}
});
}
@@ -136,11 +258,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
return;
}
}
fileUpgrade(filename, url , modulename, callback, error -> {
fileUpgrade(filename, url, modulename, callback, error -> {
if (retries >= 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
mLogin.refreshLogin(success -> {
file(filename, url, modulename, callback, errorCallback, forceRefresh, retries-1);
}, errorCallback);
}, errorCallback, url.contains("lms.fu-berlin.de") ? Login.LOGOUT_BB : Login.LOGOUT_KVV);
return;
}
errorCallback.onError(error);
@@ -148,11 +270,19 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
}
private void fileUpgrade(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
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.getLoginToken().getCookies(), response -> {
get(url, mLogin.getLoginTokenKVV().getCookies(), response -> {
if (Regex.has("\\.[Uu][Rr][Ll]$", url)){
// Return redirected URL
String path = response.getHeaders().get("Location");
@@ -166,11 +296,50 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
String path = saveFileInDownloads(filename, response.getBytes(), modulename);
callback.onResponse(path);
} else {
errorCallback.onError(new NetworkError(101704, 403, "External storage not writable!"));
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!")));
}
@@ -203,7 +372,7 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
// Saves file in folder: DOWNLOADS/moduleName
File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), moduleName);
if (!folder.mkdir()) {
if (!folder.mkdirs()) {
log.w( "Directory not created");
}
String path = "";

View File

@@ -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);
}

View File

@@ -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!")));
}
}

View File

@@ -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!")));
}
}

View File

@@ -11,7 +11,7 @@ import androidx.annotation.Nullable;
public class KVVContentProvider extends ContentProvider {
private static final String PROVIDER_NAME = "de.sebse.fuplanner.contentprovider.kvv.modules";
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;

View File

@@ -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!")));
}
}

View File

@@ -3,30 +3,71 @@ 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 com.android.volley.NetworkResponse;
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.LoginToken;
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
*/
public KVVSyncAdapter(Context context, boolean autoInitialize) {
KVVSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
init(context);
}
@@ -44,16 +85,7 @@ public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
}
private void init(Context context) {
mKVV = new KVV(new KVVListener() {
CustomAccountManager accountManager = null;
@Override
public CustomAccountManager getAccountManager() {
if (accountManager == null)
accountManager = new CustomAccountManager(AccountManager.get(context), () -> null);
return accountManager;
}
}, context);
mKVV.account().restoreOnlineLogin(bool -> {});
// Bind to LocalService
}
/*
@@ -68,20 +100,105 @@ public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
String authority,
ContentProviderClient provider,
SyncResult syncResult) {
log.d("start syncing");
/*
* Put the data transfer code here.
*/
mKVV.modules().list().recv(success -> {
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
Modules.Module module = iterator.next();
log.d("sync module", module.title);
mKVV.modules().details().recv(module, success1 -> {
if (success1.second)
log.d("Sync Successful for Module '"+module.title+"'!");
}, log::e, true);
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;
}
}, log::e, true);
mKVV.modules().list().reloadIfOutdated();
mKVV.modules().list().recv(success -> {
final int[] latch = {0};
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
latch[0] += 1;
iterator.next();
}
iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
Modules.Module module = iterator.next();
final ArrayList<Announcement> announcements = module.announcements;
final AssignmentList assignments = module.assignments;
final EventList events = module.events;
final ArrayList<Grade> gradebook = module.gradebook;
final ArrayList<Resource> resources = module.resources;
mKVV.modules().details().recv(module, success1 -> {
if (success1.second) {
sendNotifications(announcements, module.announcements, module.title, Announcement::getTitle, Announcement::getId,
module.getID(), ModulePart.ANNOUNCEMENT,
R.string.announcement_updated, R.string.announcement_added, R.string.announcement_removed);
sendNotifications(assignments, module.assignments, module.title, Assignment::getTitle, Assignment::getId,
module.getID(), ModulePart.ASSIGNMENT,
R.string.assignment_updated, R.string.assignment_added, R.string.assignment_removed);
sendNotifications(events, module.events, module.title, evt -> evt.getTitle()+" - "+UtilsDate.getModifiedDate(evt.getStartDate()), event -> String.valueOf(event.getStartDate())+event.getType()+event.getTitle(),
module.getID(), ModulePart.EVENT,
R.string.event_updated, R.string.event_added, R.string.event_removed);
sendNotifications(gradebook, module.gradebook, module.title, Grade::getItemName, Grade::getItemName,
module.getID(), ModulePart.GRADEBOOK,
R.string.gradebook_updated, R.string.gradebook_added, R.string.gradebook_removed);
sendNotifications(resources, module.resources, module.title, Resource::getTitle, Resource::getUrl,
module.getID(), ModulePart.RESOURCES,
R.string.resource_updated, R.string.resource_added, R.string.resource_removed);
if (--latch[0] == 0) mQueue.next();
}
}, error -> {
log.e(error);
if (--latch[0] == 0) mQueue.next();
}, true);
}
}, msg -> {
log.e(msg);
mQueue.next();
}, true);
});
mQueue.add(() -> {
mBound = false;
mKVV = null;
getContext().unbindService(mConnection);
});
}
private <T> void sendNotifications(Iterable<T> oldList, Iterable<T> newList, String title, StringInterface<T> titleInterface, StringInterface<T> idInterface, String moduleId, int modulePart, @StringRes int updateRes, @StringRes int addRes, @StringRes int removeRes) {
if (oldList == null || newList == null) {
return;
}
ArrayList<T> obsoletes = new ArrayList<>();
for (T old: oldList) {
obsoletes.add(old);
}
String targetData = moduleId+"."+ModulePart.getPageByPart(modulePart);
for (T newEntry: newList) {
boolean found = false;
for (T oldEntry: oldList) {
if (idInterface.get(newEntry).equals(idInterface.get(oldEntry))) {
found = true;
if (newEntry.hashCode() != oldEntry.hashCode()) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(updateRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
obsoletes.remove(oldEntry);
break;
}
}
if (!found) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(addRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
}
for (T oldEntry: obsoletes) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(removeRes, title), titleInterface.get(oldEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
}
@FunctionalInterface
interface StringInterface<T> {
String get(T element);
}
}

View File

@@ -1,306 +0,0 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class Login extends HTTPService {
public Login(Context context) {
super(context);
}
public void testLoginToken(@NotNull LoginToken token, @NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
get(String.format("https://kvv.imp.fu-berlin.de/direct/profile/%s.json", token.getUsername()), token.getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(100172, 403, "Testing login failed!"));
return;
}
try {
JSONObject json = new JSONObject(body);
String displayName = json.getString("displayName");
String email = json.getString("email");
token.setAdditionals(displayName, email);
callback.onResponse(token);
} catch (JSONException e) {
errorCallback.onError(new NetworkError(100171, 403, "Cannot parse profile!"));
}
}, error -> errorCallback.onError(new NetworkError(100170, error.networkResponse.statusCode, "Testing login failed!")));
}
public void doLogin(String username, String password, NetworkCallback<LoginToken> callback, NetworkErrorCallback error) {
startKVVSession(success -> {
String kvvJSESSIONID = success.get("JSESSIONID");
getSAMLRequest(kvvJSESSIONID, success1 -> startIdentSession(success1.get("Location"), success11 -> {
String identJSESSIONID = success11.get("JSESSIONID");
String ident_idp_authn_lc_key = success11.get("_idp_authn_lc_key");
String identROUTEID = success11.get("ROUTEID");
loginIdent(true, username, password, identJSESSIONID, ident_idp_authn_lc_key, identROUTEID, success111 -> loginIdent(false, username, password, identJSESSIONID, ident_idp_authn_lc_key, identROUTEID, success11112 -> {
String ident_idp_session = success11112.get("_idp_session");
getSAMLResponse(identJSESSIONID, ident_idp_authn_lc_key, identROUTEID, ident_idp_session, success1111 -> loginKVV(success1111.get("RelayState"), success1111.get("SAMLResponse"), kvvJSESSIONID, success111112 -> {
LoginToken token = new LoginToken(username, success111112.get("shibsessionKey"), success111112.get("shibsessionName"), kvvJSESSIONID);
finishKVVlogin(token, success11111 -> callback.onResponse(token), error);
}, error), error);
}, error), error);
}, error), error);
}, error);
}
/*
GET https://kvv.imp.fu-berlin.de/portal/login
-> JSESSIONID 5c10406f-588c-4c16-96e9-c80d115417de.tomcat1
*/
private void startKVVSession(final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
get("https://kvv.imp.fu-berlin.de/portal/login", null, response -> {
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies==null) {
errorCallback.onError(new NetworkError(100101, -1, "Error on starting KVV session!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies, new String[]{"JSESSIONID"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100102, -1, "Error on starting KVV session!"));
return;
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100100, error.networkResponse.statusCode, "Error on starting KVV session!")));
}
/*
GET https://kvv.imp.fu-berlin.de/sakai-login-tool/container
<- JSESSIONID
-> (Location-Header) https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO
?SAMLRequest=fZLLb.....Q8yre3X1IHwkJKE0Mnpy/V9TH4A
&RelayState=ss:mem:7ea01e29157b8bd906f7002176.....0d1a505f2c8bf
*/
private void getSAMLRequest(String JSESSIONID, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID);
get("https://kvv.imp.fu-berlin.de/sakai-login-tool/container", cookies, response -> {
String location = response.getHeaders().get("Location");
if (location==null) {
errorCallback.onError(new NetworkError(100111, -1, "Error on getting SAML request!"));
return;
}
HashMap<String, String> object = new HashMap<>();
object.put("Location", location);
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100110, error.networkResponse.statusCode, "Error on getting SAML request!")));
}
/*
GET https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO
?SAMLRequest=fZLLbsIwEEV/JfI+cWJAUIsgpbAoEi2IpF10UznxUKw6dupxaPn7hkdb2LD29bkzRzNGUeuGZ63fmjV8toA++K61QX58SEnrDLcCFXIjakDuK55njwvOopg3znpbWU2CDBGcV9ZMrcG2BpeD26kKnteLlGy9b5BT+rHbRapuok0bluC0MpEEmm9VWVoNfhshWnpgM7pa5gUJZt0wyogD9h+iJBiv/P6aomQTbtqSdhNtlIYzZg1SOag8zfMlCeazlLyNqpHsy1gO2V1fVsNBMuqJoUyAJaxXDUaiiyG2MDfohfEpYXEyDJM4ZKxgCe/FPI5fSbA6L36vjFTm/bal8hRC/lAUq/C02gs4PK7VBchkfHDNj8Xuwv5trPhVTiY3BeOf4DG96DmVNvypA89nK6tVtQ8yre3X1IHwkJKE0Mnpy/V9TH4A
&RelayState=ss:mem:7ea01e29157b8bd906f7002176213b6db5e1f45ebb88716a9820d1a505f2c8bf
-> JSESSIONID C4B6A428BA1F50746235D03F5D107A57
-> _idp_authn_lc_key 57a6ae26067f374cc3d0ccfc47e27b04b47752d2a3d4eb2782af0d3994535395
-> ROUTEID .1
*/
private void startIdentSession(String url, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
get(url, null, response -> {
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies==null) {
errorCallback.onError(new NetworkError(100121, -1, "Error on starting Ident session!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies, new String[]{"JSESSIONID", "_idp_authn_lc_key", "ROUTEID"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100122, -1, "Error on starting Ident session!"));
return;
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100120, error.networkResponse.statusCode, "Error on starting Ident session!")));
}
/*
POST https://identity.fu-berlin.de/idp-fub/Authn/UserPassword
<- j_username seedorf96
<- j_password neinhieristpatrick
<- (Header-"Content-Type") application/x-www-form-urlencoded
<- JSESSIONID
<- _idp_authn_lc_key
<- ROUTEID
-> _idp_session OTMuMTkzLjg1LjMz|LQ==|OGYxOWI4MjA2NTQ4YWUwYzJkOWM4Mjk4YzcwZDMwZmJiZjBmMTdmMzkyZGU2OWIwY2JkNmZlNjlmNTRmNzBlMQ==|wLlzQal7VqyntmG2vLNn06wt8wQ=
*/
private void loginIdent(final boolean first, String username, String password, String JSESSIONID, String _idp_authn_lc_key, String ROUTEID, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID);
cookies.put("_idp_authn_lc_key", _idp_authn_lc_key);
cookies.put("ROUTEID", ROUTEID);
HashMap<String, String> body = new HashMap<>();
body.put("j_username", username);
body.put("j_password", password);
post("https://identity.fu-berlin.de/idp-fub/Authn/UserPassword", cookies, body, response -> {
if (first) {
callback.onResponse(new HashMap<>());
return;
}
String cookies1 = response.getHeaders().get("Set-Cookie");
if (cookies1 ==null) {
errorCallback.onError(new NetworkError(100131, -1, "Error on logging in to Identity Server!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies1, new String[]{"_idp_session"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100132, -1, "Error on logging in to Identity Server!"));
return;
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100130, error.networkResponse.statusCode, "Error on logging in to Identity Server!")));
}
/*
GET https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO
<- JSESSIONID
<- _idp_authn_lc_key
<- ROUTEID
<- _idp_session
-> (BODY) RelayState 7ea01e29157b8bd906f7002176213b6db5e1f45ebb88716a9820d1a505f2c8bf
-> (BODY) SAMLResponse PD94bWwgdmVyc2lvbj0...........wvc2FtbDJwOlJlc3BvbnNlPg==
*/
private void getSAMLResponse(String JSESSIONID, String _idp_authn_lc_key, String ROUTEID, String _idp_session, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID);
cookies.put("_idp_authn_lc_key", _idp_authn_lc_key);
cookies.put("ROUTEID", ROUTEID);
cookies.put("_idp_session", _idp_session);
get("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO", cookies, response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(100143, -1, "Error on getting SAML response!"));
return;
}
HashMap<String, String> object = new HashMap<>();
Pattern pattern = Pattern.compile("ss&#x3a;mem&#x3a;([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;
}
}

View File

@@ -28,7 +28,7 @@ public class Announcement implements Serializable {
return urls;
}
private String getId() {
public String getId() {
return id;
}

View File

@@ -22,7 +22,7 @@ public class Assignment implements Serializable {
this.instructions = instructions;
}
private String getId() {
public String getId() {
return id;
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -118,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());
}
}

View File

@@ -6,6 +6,7 @@ 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;
@@ -36,14 +37,17 @@ public class GroupedEvents extends EventList {
return skippedDayCount;
}
public class Group {
public class Group implements Iterable<Event> {
private long firstDate;
private long lastDate;
private final ArrayList<Long> skippedDates;
private final ArrayList<Event> allEvents = new ArrayList<>();
private final int dayOfWeek;
private final long startTime;
private final long duration;
private final String location;
private final String title;
private Group(Event event) {
Calendar calendar = Calendar.getInstance();
@@ -51,6 +55,8 @@ public class GroupedEvents extends EventList {
dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
startTime = calendar.get(Calendar.HOUR_OF_DAY)*3600000+calendar.get(Calendar.MINUTE)*60000+calendar.get(Calendar.SECOND)*1000+calendar.get(Calendar.MILLISECOND);
duration = event.getEndDate()-event.getStartDate();
location = event.getLocation();
title = event.getTitle();
skippedDates = new ArrayList<>();
calendar.set(Calendar.HOUR_OF_DAY, 0);
@@ -59,6 +65,7 @@ public class GroupedEvents extends EventList {
calendar.set(Calendar.MILLISECOND, 0);
firstDate = calendar.getTimeInMillis();
lastDate = firstDate;
allEvents.add(event);
}
private boolean add(Event event) {
@@ -67,7 +74,8 @@ public class GroupedEvents extends EventList {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int startTime = calendar.get(Calendar.HOUR_OF_DAY)*3600000+calendar.get(Calendar.MINUTE)*60000+calendar.get(Calendar.SECOND)*1000+calendar.get(Calendar.MILLISECOND);
long length = event.getEndDate()-event.getStartDate();
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);
@@ -92,6 +100,7 @@ public class GroupedEvents extends EventList {
skippedDates.remove(date);
skippedDayCount -= 1;
}
allEvents.add(event);
return true;
}
@@ -126,11 +135,29 @@ public class GroupedEvents extends EventList {
return duration;
}
public String getLocation() {
return location;
}
public String getTitle() {
return title;
}
@SuppressLint("DefaultLocale")
@NonNull
@Override
public String toString() {
return String.format("%d - %d - %d - %s", dayOfWeek, startTime, duration, skippedDates);
}
@NonNull
@Override
public Iterator<Event> iterator() {
return Collections.unmodifiableList(allEvents).iterator();
}
public int size() {
return allEvents.size();
}
}
}

View File

@@ -12,6 +12,13 @@ public class Lecturer implements Serializable {
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);

View File

@@ -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);
}
}

View File

@@ -1,44 +1,34 @@
package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import com.google.android.gms.common.internal.Objects;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.Serializable;
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;
import de.sebse.fuplanner.tools.logging.Logger;
/**
* Created by sebastian on 29.10.17.
*/
public class LoginToken implements Serializable {
static Logger log = new Logger("LoginToken");
private static final String FILE_NAME = "LoginTokenSaving";
public class LoginTokenKVV {
private final String username;
private final String shibsessionKey;
private final String shibsessionName;
private final String JSESSIONID;
private boolean isAvailable = true;
@Nullable private String fullName;
@Nullable private String email;
public LoginToken(String username, String shibsessionKey, String shibsessionName, String JSESSIONID) {
public LoginTokenKVV(String username, String JSESSIONID) {
this.username = username;
this.shibsessionKey = shibsessionKey;
this.shibsessionName = shibsessionName;
this.JSESSIONID = JSESSIONID;
}
@Nullable
public static void load(CustomAccountManager manager, LoginTokenInterface callback) {
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
callback.run(null);
return;
@@ -48,8 +38,8 @@ public class LoginToken implements Serializable {
callback.run(null);
return;
}
callback.run(LoginToken.fromJsonString(tokenString));
});
callback.run(LoginTokenKVV.fromJsonString(tokenString));
}, errorCallback);
}
public void delete(CustomAccountManager manager) {
@@ -59,20 +49,23 @@ public class LoginToken implements Serializable {
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 getShibsessionKey() {
return shibsessionKey;
}
private String getShibsessionName() {
return shibsessionName;
}
private String getJSESSIONID() {
return JSESSIONID;
}
@@ -90,7 +83,6 @@ public class LoginToken implements Serializable {
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;
}
@@ -114,30 +106,30 @@ public class LoginToken implements Serializable {
JSONObject json = new JSONObject();
try {
json.put("username", username);
json.put("shibsessionKey", shibsessionKey);
json.put("shibsessionName", shibsessionName);
json.put("JSESSIONID", JSESSIONID);
json.put("fullName", fullName);
json.put("email", email);
json.put("isAvailable", isAvailable);
} catch (JSONException e) {
return null;
}
return json.toString();
}
public static LoginToken fromJsonString(String tokenString) {
private static LoginTokenKVV fromJsonString(String tokenString) {
try {
JSONObject json = new JSONObject(tokenString);
LoginToken token = new LoginToken(
LoginTokenKVV token = new LoginTokenKVV(
json.getString("username"),
json.getString("shibsessionName"),
json.getString("shibsessionName"),
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();
@@ -145,7 +137,12 @@ public class LoginToken implements Serializable {
}
}
@Override
public int hashCode() {
return Objects.hashCode(username, JSESSIONID, fullName, email);
}
public interface LoginTokenInterface {
void run(LoginToken token);
void run(LoginTokenKVV token);
}
}

View File

@@ -2,6 +2,8 @@ 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);
}
}
}

View File

@@ -62,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;
@@ -91,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 {
@@ -138,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());
}
}
}

View File

@@ -104,20 +104,22 @@ public class Download {
showDownloadError();
return;
}
activity.getKVV().modules().resources().file(file.getTitle(), file.getUrl(), folderName, success -> {
Context context = contextInterface.get();
if (success.equals("") || context== null) {
showDownloadError();
} else {
if (Regex.has("^http", success)){
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(success));
context.startActivity(intent);
activity.getKVV(kvv -> {
kvv.modules().resources().file(file.getTitle(), file.getUrl(), folderName, success -> {
Context context = contextInterface.get();
if (success.equals("") || context== null) {
showDownloadError();
} else {
if (Regex.has("^http", success)){
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(success));
context.startActivity(intent);
}
else {
fileOpen(new File(success));
}
}
else {
fileOpen(new File(success));
}
}
}, log::e, downloadNew);
}, log::e, downloadNew);
});
}
private void showDownloadError() {

View File

@@ -9,16 +9,16 @@ import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.services.kvv.Login;
import de.sebse.fuplanner.tools.logging.Logger;
public class CustomAccountManager {
private final AccountManager mAccountManager;
private final ActivityInterface mActivityInterface;
private Logger log = new Logger(this);
public CustomAccountManager(AccountManager manager, ActivityInterface activityInterface) {
mAccountManager = manager;
@@ -67,7 +67,6 @@ public class CustomAccountManager {
public void deleteAccount(String accountType) {
Account[] accounts = mAccountManager.getAccountsByType(accountType);
int[] count = {accounts.length};
for (Account account: accounts) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mAccountManager.removeAccount(account, null, null, null);
@@ -77,7 +76,7 @@ public class CustomAccountManager {
}
}
public void getTokenByType(String accountType, String authTokenType, @Nullable StringInterface callback) {
public void getTokenByType(String accountType, String authTokenType, @Nullable StringInterface callback, @Nullable ExceptionInterface errorCallback) {
Activity activity = mActivityInterface.get();
AccountManagerCallback<Bundle> cb = (accountManagerFuture -> {
try {
@@ -85,16 +84,11 @@ public class CustomAccountManager {
final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN);
if (callback != null)
callback.run(authtoken);
return;
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OperationCanceledException e) {
} catch (AuthenticatorException | IOException | OperationCanceledException e) {
e.printStackTrace();
if (errorCallback != null)
errorCallback.run(e);
}
if (callback != null)
callback.run(null);
});
if (activity != null) {
mAccountManager.getAuthTokenByFeatures(accountType, authTokenType, null, mActivityInterface.get(), null, null, cb, null);
@@ -122,6 +116,13 @@ public class CustomAccountManager {
return mAccountManager.getAccountsByType(accountType).length != 0;
}
public Account getAccountByType(String accountType) {
Account[] accountsByType = mAccountManager.getAccountsByType(accountType);
if (accountsByType.length > 0)
return accountsByType[0];
return null;
}
@FunctionalInterface
public interface ActivityInterface {
@Nullable
@@ -131,4 +132,8 @@ public class CustomAccountManager {
public interface StringInterface {
void run(@Nullable String string);
}
public interface ExceptionInterface {
void run(@NotNull Exception string);
}
}

View File

@@ -0,0 +1,65 @@
package de.sebse.fuplanner.tools;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import org.jetbrains.annotations.NotNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
public class CustomNotificationManager {
private static final String CHANNEL_ID = "fuplanner-default";
public static final String NOTIFICATION_INTENT = "notification-intent";
public static final String NOTIFICATION_PAGE = "notification-page";
public static final String NOTIFICATION_DATA = "notification-data";
public static final String NOTIFICATION_TYPE_NAVIGATE = "navigate";
//public static ArrayList<Integer> passedNotifications = new ArrayList<>();
public static void sendNotification(Context context, String textTitle, String textContent, int page, String data) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(NOTIFICATION_INTENT, NOTIFICATION_TYPE_NAVIGATE);
intent.putExtra(NOTIFICATION_PAGE, page);
intent.putExtra(NOTIFICATION_DATA, data);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
int notificationId = (int) (System.currentTimeMillis() % Integer.MAX_VALUE);
notificationManager.notify(notificationId, mBuilder.build());
}
public static void createNotificationChannel(@NotNull Context context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
}
}

View File

@@ -2,8 +2,10 @@ package de.sebse.fuplanner.tools;
import androidx.annotation.StringRes;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.news.NewsManager;
public interface MainActivityListener {
@@ -15,7 +17,7 @@ public interface MainActivityListener {
void showToast(@StringRes int msgStringRes);
KVV getKVV();
void getKVV(MainActivity.KVVCallback kvv);
CanteenBrowser getCanteenBrowser();

View File

@@ -5,12 +5,13 @@ import android.util.Pair;
import java.util.HashSet;
import java.util.Iterator;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class NetworkCallbackCollector<T> extends HashSet<Pair<NetworkCallback<T>, NetworkErrorCallback>> {
public void add(NetworkCallback<T> success, NetworkErrorCallback error) {
public void add(@Nullable NetworkCallback<T> success, @Nullable NetworkErrorCallback error) {
add(new Pair<>(success, error));
}
@@ -18,7 +19,8 @@ public class NetworkCallbackCollector<T> extends HashSet<Pair<NetworkCallback<T>
Iterator<Pair<NetworkCallback<T>, NetworkErrorCallback>> i;
for (i = this.iterator(); i.hasNext();) {
Pair<NetworkCallback<T>, NetworkErrorCallback> pair = i.next();
pair.second.onError(error);
if (pair.second != null)
pair.second.onError(error);
i.remove();
}
}
@@ -27,7 +29,8 @@ public class NetworkCallbackCollector<T> extends HashSet<Pair<NetworkCallback<T>
Iterator<Pair<NetworkCallback<T>, NetworkErrorCallback>> i;
for (i = this.iterator(); i.hasNext();) {
Pair<NetworkCallback<T>, NetworkErrorCallback> pair = i.next();
pair.first.onResponse(success);
if (pair.first != null)
pair.first.onResponse(success);
i.remove();
}
}

View File

@@ -2,6 +2,7 @@ package de.sebse.fuplanner.tools;
import java.util.LinkedList;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
@@ -9,6 +10,9 @@ public class NewAsyncQueue {
private final LinkedList<AsyncQueueCallback> mQueue = new LinkedList<>();
private boolean mIsRunning = false;
public NewAsyncQueue() {
}
public void add(AsyncQueueCallback callback) {
if (isRunning())
getQueue().addLast(callback);

View File

@@ -1,23 +1,42 @@
package de.sebse.fuplanner.tools;
import android.content.Context;
import androidx.annotation.ArrayRes;
import androidx.annotation.StringRes;
import androidx.preference.PreferenceManager;
public class Preferences {
public static String getString(Context context, @ArrayRes int key) {
public static String getStringArray(Context context, @ArrayRes int key) {
String[] strings = context.getResources().getStringArray(key);
return PreferenceManager.getDefaultSharedPreferences(context).getString(strings[0], strings[1]);
}
public static String getString(Context context, @StringRes int key) {
String string = context.getResources().getString(key);
return PreferenceManager.getDefaultSharedPreferences(context).getString(string, null);
}
public static void setString(Context context, @StringRes int key, String value) {
String string = context.getResources().getString(key);
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(string, value).apply();
}
public static long getLong(Context context, @StringRes int key) {
String string = context.getResources().getString(key);
return PreferenceManager.getDefaultSharedPreferences(context).getLong(string, 0);
}
public static void setLong(Context context, @StringRes int key, long value) {
String string = context.getResources().getString(key);
PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(string, value).apply();
}
public static boolean getBoolean(Context context, @StringRes int key) {
String string = context.getResources().getString(key);
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(string, false);
}
public static void setBoolean(Context context, @StringRes int key, boolean value) {
String string = context.getResources().getString(key);
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(string, value).apply();
}
}

View File

@@ -30,6 +30,15 @@ public class Regex {
return matcher.group(group);
}
public static Matcher match(@Language("Regexp") String regex, String match) throws NoSuchFieldException {
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(match);
if (!matcher.find()) {
throw new NoSuchFieldException(String.format("Pattern: %s - String: %s", regex, match));
}
return matcher;
}
public static Iterable<MatchResult> allMatches(@Language("Regexp") String regex, final CharSequence input) {
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
return () -> new Iterator<MatchResult>() {

View File

@@ -0,0 +1,225 @@
package de.sebse.fuplanner.tools.network;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.EventListener;
import de.sebse.fuplanner.tools.logging.Logger;
/**
* Created by sebastian on 24.10.17.
*/
public class HTTPNetwork extends Service {
private RequestQueue requestQueue;
protected final Logger log = new Logger(this);
private final EventListener<VolleyError> errorResponseListener = new EventListener<>();
private final EventListener<Result> successResponseListener = new EventListener<>();
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
@Override
public void onCreate() {
super.onCreate();
requestQueue = Volley.newRequestQueue(getApplicationContext(), new BetterHurlStack(false));
}
public void addErrorListener(String id, EventListener.EventFunction<VolleyError> listener) {
errorResponseListener.add(id, listener);
}
public void removeErrorListener(String id) {
errorResponseListener.remove(id);
}
public void addSuccessListener(String id, EventListener.EventFunction<Result> listener) {
successResponseListener.add(id, listener);
}
public void removeSuccessListener(String id) {
successResponseListener.remove(id);
}
protected void head(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
get(url, cookies, response, error, true);
}
protected void get(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
get(url, cookies, response, error, false);
}
private void get(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error, boolean noBody) {
int requestMethod = noBody ? Request.Method.HEAD : Request.Method.GET;
HttpRequest request = new HttpRequest(requestMethod, url, response, error) {
@Override
public void deliverError(VolleyError error) {
if (error == null) {
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
} else if (error.networkResponse == null) {
int statusCode;
if (error instanceof TimeoutError)
statusCode = 408;
else
statusCode = 500;
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
} else {
final int status = error.networkResponse.statusCode;
if (status == 302) {
deliverResponse(new Result(null, error.networkResponse.headers));
} else {
deliver(error);
}
}
}
@Override
protected void deliverResponse(Result response) {
successResponseListener.emit(response);
super.deliverResponse(response);
}
private void deliver(VolleyError error) {
errorResponseListener.emit(error);
super.deliverError(error);
}
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = super.getHeaders();
if (cookies != null) {
if (params==null)
params = new HashMap<>();
else
params = new HashMap<>(params);
StringBuilder newStr = new StringBuilder();
for (String key : cookies.keySet())
newStr.append(key).append("=").append(cookies.get(key)).append(";");
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
params.put("Cookie", newStr.toString());
}
return params;
}
};
requestQueue.add(request);
}
protected void post(String url, @Nullable final HashMap<String, String> cookies, @Nullable final HashMap<String, String> body, Response.Listener<Result> response, Response.ErrorListener error) {
HttpRequest request = new HttpRequest(Request.Method.POST, url, response, error) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
public byte[] getBody() {
if (body==null) {
return null;
}
StringBuilder sb = new StringBuilder();
for(HashMap.Entry<String, String> e: body.entrySet()){
if(sb.length() > 0){
sb.append('&');
}
try {
sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException ignored) {
}
}
String requestBody = sb.toString();
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
@Override
public void deliverError(VolleyError error) {
if (error == null) {
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
} else if (error.networkResponse == null) {
int statusCode;
if (error instanceof TimeoutError)
statusCode = 408;
else
statusCode = 500;
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
} else {
final int status = error.networkResponse.statusCode;
if (status == 302) {
deliverResponse(new Result(null, error.networkResponse.headers));
} else {
deliver(error);
}
}
}
private void deliver(VolleyError error) {
errorResponseListener.emit(error);
super.deliverError(error);
}
@Override
protected void deliverResponse(Result response) {
successResponseListener.emit(response);
super.deliverResponse(response);
}
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = super.getHeaders();
if (cookies != null) {
if (params==null)
params = new HashMap<>();
else
params = new HashMap<>(params);
StringBuilder newStr = new StringBuilder();
for (String key : cookies.keySet())
newStr.append(key).append("=").append(cookies.get(key)).append(";");
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
params.put("Cookie", newStr.toString());
}
return params;
}
};
requestQueue.add(request);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public HTTPNetwork getService() {
// Return this instance of LocalService so clients can call public methods
return HTTPNetwork.this;
}
}
}

View File

@@ -1,23 +1,22 @@
package de.sebse.fuplanner.tools.network;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.CountDownTimer;
import android.os.IBinder;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.EventListener;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.logging.Logger;
/**
@@ -25,167 +24,172 @@ import de.sebse.fuplanner.tools.logging.Logger;
*/
public class HTTPService {
private final RequestQueue requestQueue;
private final Context mContext;
private NewAsyncQueue mQueue = new NewAsyncQueue();
protected final Logger log = new Logger(this);
private final EventListener<VolleyError> errorResponseListener = new EventListener<>();
private final EventListener<Result> successResponseListener = new EventListener<>();
private int mRequestCount = 0;
private final HashMap<String, EventListener.EventFunction<VolleyError>> errorListeners = new HashMap<>();
private final HashMap<String, EventListener.EventFunction<Result>> successListeners = new HashMap<>();
private CountDownTimer mDisconnectTimer = null;
private HTTPNetwork mService;
private boolean mBound = false;
private boolean mWaitForBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
HTTPNetwork.LocalBinder binder = (HTTPNetwork.LocalBinder) service;
mService = binder.getService();
mBound = true;
for (String listenerKey: errorListeners.keySet()) {
mService.addErrorListener(listenerKey, errorListeners.get(listenerKey));
}
for (String listenerKey: successListeners.keySet()) {
mService.addSuccessListener(listenerKey, successListeners.get(listenerKey));
}
if (mWaitForBound) {
mWaitForBound = false;
mQueue.next();
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mService = null;
}
};
public HTTPService(Context context) {
this.mContext = context;
requestQueue = Volley.newRequestQueue(context, new BetterHurlStack(false));
}
public void addErrorListener(String id, EventListener.EventFunction<VolleyError> listener) {
errorResponseListener.add(id, listener);
errorListeners.put(id, listener);
connect();
mQueue.add(() -> {
mService.addErrorListener(id, listener);
mQueue.next();
disconnect();
});
}
public void removeErrorListener(String id) {
errorResponseListener.remove(id);
errorListeners.remove(id);
connect();
mQueue.add(() -> {
mService.removeErrorListener(id);
mQueue.next();
disconnect();
});
}
public void addSuccessListener(String id, EventListener.EventFunction<Result> listener) {
successResponseListener.add(id, listener);
successListeners.put(id, listener);
connect();
mQueue.add(() -> {
mService.addSuccessListener(id, listener);
mQueue.next();
disconnect();
});
}
public void removeSuccessListener(String id) {
successResponseListener.remove(id);
successListeners.remove(id);
connect();
mQueue.add(() -> {
mService.removeSuccessListener(id);
mQueue.next();
disconnect();
});
}
protected void head(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
connect();
mQueue.add(() -> {
mService.head(url, cookies, response1 -> {
response.onResponse(response1);
disconnect();
}, error1 -> {
error.onErrorResponse(error1);
disconnect();
});
mQueue.next();
});
}
protected void get(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
HttpRequest request = new HttpRequest(Request.Method.GET, url, response, error) {
@Override
public void deliverError(VolleyError error) {
if (error == null) {
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
} else if (error.networkResponse == null) {
int statusCode;
if (error instanceof TimeoutError)
statusCode = 408;
else
statusCode = 500;
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
} else {
final int status = error.networkResponse.statusCode;
if (status == 302) {
deliverResponse(new Result(null, error.networkResponse.headers));
} else {
deliver(error);
}
}
}
@Override
protected void deliverResponse(Result response) {
successResponseListener.emit(response);
super.deliverResponse(response);
}
private void deliver(VolleyError error) {
errorResponseListener.emit(error);
super.deliverError(error);
}
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = super.getHeaders();
if (cookies != null) {
if (params==null)
params = new HashMap<>();
else
params = new HashMap<>(params);
StringBuilder newStr = new StringBuilder();
for (String key : cookies.keySet())
newStr.append(key).append("=").append(cookies.get(key)).append(";");
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
params.put("Cookie", newStr.toString());
}
return params;
}
};
requestQueue.add(request);
connect();
mQueue.add(() -> {
mService.get(url, cookies, response1 -> {
response.onResponse(response1);
disconnect();
}, error1 -> {
error.onErrorResponse(error1);
disconnect();
});
mQueue.next();
});
}
protected void post(String url, @Nullable final HashMap<String, String> cookies, @Nullable final HashMap<String, String> body, Response.Listener<Result> response, Response.ErrorListener error) {
HttpRequest request = new HttpRequest(Request.Method.POST, url, response, error) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
connect();
mQueue.add(() -> {
mService.post(url, cookies, body, response1 -> {
response.onResponse(response1);
disconnect();
}, error1 -> {
error.onErrorResponse(error1);
disconnect();
});
mQueue.next();
});
}
@Override
public byte[] getBody() {
if (body==null) {
return null;
}
StringBuilder sb = new StringBuilder();
for(HashMap.Entry<String, String> e: body.entrySet()){
if(sb.length() > 0){
sb.append('&');
}
try {
sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException ignored) {
}
}
String requestBody = sb.toString();
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
private void connect() {
if (!mBound) {
Intent intent = new Intent(getContext(), HTTPNetwork.class);
getContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
if (!mWaitForBound) mQueue.add(() -> {});
mWaitForBound = true;
}
if (mDisconnectTimer != null) {
mDisconnectTimer.cancel();
mDisconnectTimer = null;
}
mRequestCount++;
}
@Override
public void deliverError(VolleyError error) {
if (error == null) {
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
} else if (error.networkResponse == null) {
int statusCode;
if (error instanceof TimeoutError)
statusCode = 408;
else
statusCode = 500;
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
} else {
final int status = error.networkResponse.statusCode;
if (status == 302) {
deliverResponse(new Result(null, error.networkResponse.headers));
} else {
deliver(error);
}
}
private void disconnect() {
mRequestCount--;
if (mDisconnectTimer == null) {
if (mBound && mRequestCount == 0) {
mBound = false;
mService = null;
getContext().unbindService(mConnection);
}
}
}
private void deliver(VolleyError error) {
errorResponseListener.emit(error);
super.deliverError(error);
}
@Override
protected void deliverResponse(Result response) {
successResponseListener.emit(response);
super.deliverResponse(response);
}
protected String getCookie(String cookies, String name) throws NoSuchFieldException {
Pattern pattern = Pattern.compile(name+"=([^;]+);");
Matcher matcher = pattern.matcher(cookies);
if (!matcher.find()) {
log.e("GETcookie failed", name);
log.e("GETcookie failed", cookies);
throw new NoSuchFieldException();
}
return matcher.group(1);
}
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = super.getHeaders();
if (cookies != null) {
if (params==null)
params = new HashMap<>();
else
params = new HashMap<>(params);
StringBuilder newStr = new StringBuilder();
for (String key : cookies.keySet())
newStr.append(key).append("=").append(cookies.get(key)).append(";");
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
params.put("Cookie", newStr.toString());
}
return params;
}
};
requestQueue.add(request);
protected 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;
}
protected Context getContext() {

View File

@@ -11,6 +11,7 @@ import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.Transformation;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
@@ -63,13 +64,15 @@ public class ExpandableCardView extends CardView {
private int collapsedHeight = 0;
private int expandedHeight = 0;
LayoutParams layoutParamsPreset = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
private OnExpandedListener listener;
private final Logger log = new Logger(this);
private final OnClickListener defaultClickListener = v -> {
if(isExpanded()) collapse();
else expand();
};
private final Logger log = new Logger(this);
public ExpandableCardView(Context context) {
super(context);
@@ -134,6 +137,10 @@ public class ExpandableCardView extends CardView {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (outerView == null || innerView == null) {
log.w("This should not happen (onLayout)! Inner views are null!", innerView, outerView);
return;
}
removeAllViews();
int x = getPaddingLeft();
int y = getPaddingTop();
@@ -153,7 +160,12 @@ public class ExpandableCardView extends CardView {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (MeasureSpec.getSize(widthMeasureSpec) == 0 && MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED || MeasureSpec.getSize(heightMeasureSpec) == 0 && MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.UNSPECIFIED) {
log.w("This should not happen! Invalid dimension size");
log.w("This should not happen (onMeasure)! Invalid dimension size");
setMeasuredDimension(reconcileSize(10, widthMeasureSpec), reconcileSize(10, heightMeasureSpec));
return;
}
if (outerView == null || innerView == null) {
log.w("This should not happen (onMeasure)! Inner views are null!", innerView, outerView);
setMeasuredDimension(reconcileSize(10, widthMeasureSpec), reconcileSize(10, heightMeasureSpec));
return;
}
@@ -167,12 +179,14 @@ public class ExpandableCardView extends CardView {
widthMeasure = atMostExactlySpec(Math.max(0, MeasureSpec.getSize(widthMeasureSpec)-imageButton.getMeasuredWidth()), widthMeasureSpec);
heightMeasure = atMostSpec(MeasureSpec.getSize(heightMeasureSpec), heightMeasureSpec);
outerView.setLayoutParams(layoutParamsPreset);
outerView.measure(widthMeasure, heightMeasure);
desiredWidth = imageButton.getMeasuredWidth() + outerView.getMeasuredWidth();
desiredHeight = Math.max(imageButton.getMeasuredHeight(), outerView.getMeasuredHeight());
widthMeasure = atMostSpec(MeasureSpec.getSize(widthMeasureSpec), widthMeasureSpec);
heightMeasure = atMostSpec(Math.max(0, MeasureSpec.getSize(heightMeasureSpec)-desiredHeight), heightMeasureSpec);
innerView.setLayoutParams(layoutParamsPreset);
innerView.measure(widthMeasure, heightMeasure);
desiredWidth = Math.max(desiredWidth, innerView.getMeasuredWidth());
desiredHeight += innerView.getMeasuredHeight();
@@ -366,4 +380,3 @@ public class ExpandableCardView extends CardView {
}

View File

@@ -0,0 +1,81 @@
package de.sebse.fuplanner.tools.ui.treeview;
import android.view.View;
import android.widget.TextView;
import com.cunoraz.tagview.Tag;
import com.cunoraz.tagview.TagView;
import androidx.core.content.ContextCompat;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.types.Resource;
import de.sebse.fuplanner.services.kvv.ui.Download;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.ui.cardview.ExpandableCardView;
/**
* Created by tlh on 2016/10/1 :)
*/
public class DocumentNodeBinder extends TreeViewBinder<DocumentNodeBinder.ViewHolder> {
private Download.OnDownloadRequestInterface requestInterface;
public DocumentNodeBinder(Download.OnDownloadRequestInterface requestInterface) {
super();
this.requestInterface = requestInterface;
}
@Override
public ViewHolder provideViewHolder(View itemView) {
return new ViewHolder(itemView);
}
@Override
public void bindView(ViewHolder holder, int position, TreeNode node) {
Resource.Document fileNode = (Resource.Document) node.getContent();
holder.title.setText(fileNode.getTitle());
holder.sub_title.setText(UtilsDate.getModifiedDateTime(holder.itemView.getContext(), fileNode.getModifiedDate()));
holder.notes.setText(fileNode.getBody());
holder.mTagGroup.removeAll();
for (int i = 0, notesSize = fileNode.size(); i < notesSize; i++) {
String name = fileNode.getUrl(i).name;
Tag tag = new Tag(name.substring(0, Math.min(40, name.length())));
tag.id = i;
tag.layoutColor = ContextCompat.getColor(holder.itemView.getContext(), R.color.colorFUBlue);
holder.mTagGroup.addTag(tag);
}
holder.mTagGroup.setOnTagClickListener((tag, i) -> {
String s = fileNode.getUrl(i).url;
if (s != null) {
String name = fileNode.getUrl(i).name;
this.requestInterface.request(name, s);
}
});
holder.itemView.invalidate();
}
@Override
public int getLayoutId() {
return R.layout.list_announcement_items;
}
public class ViewHolder extends TreeViewBinder.ViewHolder {
final TextView title;
final TextView sub_title;
final TextView notes;
final ExpandableCardView card_view;
final TagView mTagGroup;
ViewHolder(View rootView) {
super(rootView);
this.card_view = rootView.findViewById(R.id.card_view);
this.title = this.card_view.getOuterView().findViewById(R.id.title);
this.sub_title = this.card_view.getOuterView().findViewById(R.id.sub_title);
this.notes = this.card_view.getInnerView().findViewById(R.id.notes);
this.mTagGroup = this.card_view.getInnerView().findViewById(R.id.tag_group);
}
}
}

View File

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

View File

@@ -88,32 +88,34 @@ public class TreeViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
holder.itemView.setPadding(displayNodes.get(position).getHeight() * padding, 3, 3, 3);
holder.itemView.setOnClickListener(v -> {
TreeNode selectedNode = displayNodes.get(holder.getLayoutPosition());
// Prevent multi-click during the short interval.
try {
long lastClickTime = (long) holder.itemView.getTag();
if (System.currentTimeMillis() - lastClickTime < 500)
return;
} catch (Exception e) {
if (!holder.itemView.hasOnClickListeners()) {
holder.itemView.setOnClickListener(v -> {
TreeNode selectedNode = displayNodes.get(holder.getLayoutPosition());
// Prevent multi-click during the short interval.
try {
long lastClickTime = (long) holder.itemView.getTag();
if (System.currentTimeMillis() - lastClickTime < 500)
return;
} catch (Exception e) {
holder.itemView.setTag(System.currentTimeMillis());
}
holder.itemView.setTag(System.currentTimeMillis());
}
holder.itemView.setTag(System.currentTimeMillis());
if (onTreeNodeListener != null && onTreeNodeListener.onClick(selectedNode, holder))
return;
if (selectedNode.isLeaf())
return;
// This TreeNode was locked to click.
if (selectedNode.isLocked()) return;
boolean isExpand = selectedNode.isExpand();
int positionStart = displayNodes.indexOf(selectedNode) + 1;
if (!isExpand) {
notifyItemRangeInserted(positionStart, addChildNodes(selectedNode, positionStart));
} else {
notifyItemRangeRemoved(positionStart, removeChildNodes(selectedNode, true));
}
});
if (onTreeNodeListener != null && onTreeNodeListener.onClick(selectedNode, holder))
return;
if (selectedNode.isLeaf())
return;
// This TreeNode was locked to click.
if (selectedNode.isLocked()) return;
boolean isExpand = selectedNode.isExpand();
int positionStart = displayNodes.indexOf(selectedNode) + 1;
if (!isExpand) {
notifyItemRangeInserted(positionStart, addChildNodes(selectedNode, positionStart));
} else {
notifyItemRangeRemoved(positionStart, removeChildNodes(selectedNode, true));
}
});
}
for (TreeViewBinder viewBinder : viewBinders) {
if (viewBinder.getLayoutId() == displayNodes.get(position).getContent().getLayoutId())
//noinspection unchecked

View File

@@ -365,7 +365,7 @@ public class WeekView extends View {
}
int nonRoundedMinutes = selectedTime.get(Calendar.MINUTE);
int mod = nonRoundedMinutes % mNewEventTimeResolutionInMinutes;
selectedTime.add(Calendar.MINUTE, mod < Math.ceil(mNewEventTimeResolutionInMinutes / 2) ? -mod : (mNewEventTimeResolutionInMinutes - mod));
selectedTime.add(Calendar.MINUTE, mod < Math.ceil(mNewEventTimeResolutionInMinutes / 2.0) ? -mod : (mNewEventTimeResolutionInMinutes - mod));
Calendar endTime = (Calendar) selectedTime.clone();
@@ -379,8 +379,8 @@ public class WeekView extends View {
WeekViewEvent newEvent = new WeekViewEvent(mNewEventIdentifier, "", null, selectedTime, endTime);
float top = mHourHeight * getPassedMinutesInDay(selectedTime) / 60 + getEventsTop();
float bottom = mHourHeight * getPassedMinutesInDay(endTime) / 60 + getEventsTop();
float top = mHourHeight * getPassedMinutesInDay(selectedTime) / 60f + getEventsTop();
float bottom = mHourHeight * getPassedMinutesInDay(endTime) / 60f + getEventsTop();
// Calculate left and right.
float left = mWidthPerDay * daysBetween(getFirstVisibleDay(), selectedTime);
@@ -1117,7 +1117,7 @@ public class WeekView extends View {
canvas.drawRoundRect(eventRect.rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint);
float topToUse = top;
if (eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) < mMinTime)
topToUse = mHourHeight * getPassedMinutesInDay(mMinTime, 0) / 60 + getEventsTop();
topToUse = mHourHeight * getPassedMinutesInDay(mMinTime, 0) / 60f + getEventsTop();
if (!mNewEventIdentifier.equals(eventRect.event.getIdentifier()))
drawEventTitle(eventRect.event, eventRect.rectF, canvas, topToUse, left);

Binary file not shown.

After

Width:  |  Height:  |  Size: 427 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 472 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 879 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:itemTextColor="@color/menu_text_color"
app:itemIconTint="@color/menu_text_color"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
<include
layout="@layout/app_bar_main"
android:id="@+id/app_bar_include"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>

View File

@@ -41,16 +41,24 @@
android:layout_gravity="center_horizontal"
android:contentDescription="@string/cd_ic_launcher"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/error_textview"
android:textAppearance="@style/TextAppearance.Design.Error"
android:textColor="@color/colorFURed"
tools:text="@string/hello_blank_fragment" />
<!-- Email Label -->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="@+id/input_username"
<com.google.android.material.textfield.TextInputEditText android:id="@+id/input_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:inputType="textNoSuggestions"
android:hint="@string/username"
android:autofillHints="username"
tools:targetApi="o" />
@@ -62,7 +70,7 @@
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="@+id/input_password"
<com.google.android.material.textfield.TextInputEditText android:id="@+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"

View File

@@ -2,6 +2,7 @@
<de.sebse.fuplanner.tools.ui.cardview.ExpandableCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/cardview_margin"

View File

@@ -20,6 +20,7 @@
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textSize="16sp"
android:textIsSelectable="true"
android:textColor="#666666" />
<ImageButton
android:id="@id/expand_collapse"

View File

@@ -21,6 +21,7 @@
android:typeface="sans"
android:gravity="center"
android:textColor="@color/colorFUBlue"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@id/guideline"
/>
@@ -34,6 +35,7 @@
android:typeface="sans"
android:gravity="center"
android:textColor="@color/colorFUBlue"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="@id/guideline"
/>

View File

@@ -54,6 +54,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/cardview_padding"
android:textIsSelectable="true"
tools:text="@string/lorem_ipsum_100" />
</LinearLayout>

View File

@@ -6,4 +6,13 @@
<item>Angestellter</item>
<item>Andere</item>
</string-array>
<string-array name="pref_sync_frequency_entries">
<item>Jede Stunde</item>
<item>Alle 2 Stunden</item>
<item>Alle 4 Stunden</item>
<item>Alle 6 Stunden</item>
<item>Alle 12 Stunden</item>
<item>Alle 24 Stunden</item>
</string-array>
</resources>

View File

@@ -43,6 +43,9 @@
<string name="pref_price_group_title">Kantinenpreisgruppe</string>
<string name="pref_price_group_summary">Zeige nur Preise einer Gruppe</string>
<string name="pref_price_group_dialog">Preisgruppe</string>
<string name="pref_sync_frequency_title">Synchronisationshäufigkeit</string>
<string name="pref_sync_frequency_summary">Stellt Häufigkeit der automatischen Synchronisation ein</string>
<string name="pref_sync_frequency_dialog">Sync-Frequenz</string>
<string name="meals">Hauptgerichte</string>
<string name="special_meals">Spezial Gerichte</string>
<string name="side_dishes">Beilagen</string>
@@ -92,4 +95,23 @@
<string name="error_incorrect_password">Das Passwort ist nicht korrekt.</string>
<string name="error_field_required">Pflichtfeld</string>
<string name="kvv_sync">KVV-Synchronisation</string>
<string name="channel_name">Neue Daten verfügbar</string>
<string name="channel_description">Benachrichtigen, wenn neue Ankündigungen, Aufgaben, Noten oder Ressourcen verfügbar sind</string>
<string name="announcement_updated">Ankündigung aktualisiert: %1$s</string>
<string name="assignment_updated">Aufgabe aktualisiert: %1$s</string>
<string name="event_updated">Event aktualisiert: %1$s</string>
<string name="gradebook_updated">Noteneintrag aktualisiert: %1$s</string>
<string name="resource_updated">Ressource aktualisiert: %1$s</string>
<string name="announcement_added">Neue Ankündigung: %1$s</string>
<string name="assignment_added">Neue Aufgabe: %1$s</string>
<string name="event_added">Neues Event: %1$s</string>
<string name="gradebook_added">Neuer Noteneintrag: %1$s</string>
<string name="resource_added">Neue Ressource: %1$s</string>
<string name="announcement_removed">Ankündigung entfernt: %1$s</string>
<string name="assignment_removed">Aufgabe entfernt: %1$s</string>
<string name="event_removed">Event entfernt: %1$s</string>
<string name="gradebook_removed">Noteneintrag entfernt: %1$s</string>
<string name="resource_removed">Ressource entfernt: %1$s</string>
<string name="network_error">Ein Netzwerkfehler ist aufgetreten!</string>
<string name="network_error_parameter">Ein Netzwerkfehler ist aufgetreten: %s!</string>
</resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="isDrawerFixed">true</bool>
</resources>

View File

@@ -12,4 +12,21 @@
<item>employee</item>
<item>other</item>
</string-array>
<string-array name="pref_sync_frequency_entries">
<item>Every hour</item>
<item>Every 2 hours</item>
<item>Every 4 hours</item>
<item>Every 6 hours</item>
<item>Every 12 hours</item>
<item>Every 24 hours</item>
</string-array>
<string-array name="pref_sync_frequency_values" translatable="false">
<item>1</item>
<item>2</item>
<item>4</item>
<item>6</item>
<item>12</item>
<item>24</item>
</string-array>
</resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="isDrawerFixed">false</bool>
</resources>

View File

@@ -8,4 +8,15 @@
<string name="pref_price_group_default" translatable="false">all</string>
<string name="pref_last_visited_news" translatable="false">pref_last_visited_news</string>
<string name="pref_set_auto_sync_on_startup" translatable="false">pref_set_auto_sync_on_startup</string>
<string name="pref_shib_idp_session" translatable="false">pref_shib_idp_session</string>
<string-array name="pref_sync_frequency" translatable="false">
<item>@string/pref_sync_frequency</item>
<item>@string/pref_sync_frequency_default</item>
</string-array>
<string name="pref_sync_frequency" translatable="false">pref_sync_frequency</string>
<string name="pref_sync_frequency_default" translatable="false">6</string>
</resources>

View File

@@ -50,6 +50,9 @@
<string name="pref_price_group_title">Canteen Price Group</string>
<string name="pref_price_group_summary">Only show specific price category</string>
<string name="pref_price_group_dialog">Price Group Selection</string>
<string name="pref_sync_frequency_title">Sync frequency</string>
<string name="pref_sync_frequency_summary">Set automatic background sync frequency</string>
<string name="pref_sync_frequency_dialog">Frequency selection</string>
<string name="meals">Meals</string>
<string name="special_meals">Special meals</string>
<string name="side_dishes">Side Dishes</string>
@@ -100,4 +103,23 @@
<string name="error_incorrect_password">This password is incorrect</string>
<string name="error_field_required">This field is required</string>
<string name="kvv_sync">KVV Synchronization</string>
<string name="channel_name">New data available</string>
<string name="channel_description">Notify when new announcements, assignments, grades or resources are available</string>
<string name="announcement_updated">Announcement updated: %1$s</string>
<string name="announcement_added">New announcement: %1$s</string>
<string name="announcement_removed">Announcement removed: %1$s</string>
<string name="assignment_updated">Assignment updated: %1$s</string>
<string name="assignment_added">New assignment: %1$s</string>
<string name="assignment_removed">Assignment removed: %1$s</string>
<string name="event_updated">Event updated: %1$s</string>
<string name="event_added">New event: %1$s</string>
<string name="event_removed">Event removed: %1$s</string>
<string name="gradebook_updated">Gradebook entry updated: %1$s</string>
<string name="gradebook_added">New gradebook entry: %1$s</string>
<string name="gradebook_removed">Gradebook entry removed: %1$s</string>
<string name="resource_updated">Resource updated: %1$s</string>
<string name="resource_added">New resource: %1$s</string>
<string name="resource_removed">Resource removed: %1$s</string>
<string name="network_error">A network error occurred!</string>
<string name="network_error_parameter">A network error occurred: %s!</string>
</resources>

View File

@@ -9,6 +9,14 @@
android:entries="@array/pref_price_group_entries"
android:entryValues="@array/pref_price_group_values"
android:dialogTitle="@string/pref_price_group_dialog" />
<ListPreference
android:key="@string/pref_sync_frequency"
android:defaultValue="@string/pref_sync_frequency_default"
android:title="@string/pref_sync_frequency_title"
android:summary="@string/pref_sync_frequency_summary"
android:entries="@array/pref_sync_frequency_entries"
android:entryValues="@array/pref_sync_frequency_values"
android:dialogTitle="@string/pref_sync_frequency_dialog" />
<PreferenceScreen
android:title="@string/open_data_policy"
android:summary="@string/open_data_policy_summary">

View File

@@ -1,17 +0,0 @@
package de.sebse.fuplanner;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

View File

@@ -9,8 +9,7 @@ buildscript {
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.0.0'
classpath 'com.android.tools.build:gradle:3.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

89
docs/blackboard.txt Normal file
View File

@@ -0,0 +1,89 @@
## Used cookies
s_session_id
session_id
## Get user profile and ID
https://lms.fu-berlin.de/learn/api/v1/users/?userName=seedorf96
https://lms.fu-berlin.de/learn/api/v1/users/_203980_1
## Course list
https://lms.fu-berlin.de/learn/api/public/v1/users/_203980_1/courses
## Course details
https://lms.fu-berlin.de/learn/api/public/v1/courses/_122802_1
The field "courseId" in Blackboard can be matched to "props/kvv_lvnumbers" in "http://kvv.imp.fu-berlin.de/direct/site/<SITE_ID>"
- details
+ semester
* type: parse "courseId"
* year: parse "courseId"
+ lvNumber
* parse "courseId"
+ title
* "name"
+ lecturer
* https://lms.fu-berlin.de/learn/api/public/v1/courses/_127131_1/users
* Find Instructor
* Resolve "userId" to name
+ type
* parse "courseId" ('Vorlesung'/'Seminar'/...?)
+ description
* ""
+ ID
* id
## Course annoncements
https://lms.fu-berlin.de/learn/api/v1/courses/_127131_1/announcements?limit=1000&offset=0
- catch 400 (tool is not available)
- details
+ id
* "id"
+ title
* "title"
+ body
* "body/rawText"
+ createdBy
* "creatorUserId"
* search user name by id
+ createdOn
* "startDateRestriction"
+ urls
* not available / empty
## Course resources
https://lms.fu-berlin.de/learn/api/public/v1/courses/_127131_1/contents
- details
+ author
* folder: N/A
* file: N/A
+ modifiedDate
* folder: "created"
* file: "created"
+ title
* folder: "title"
* file: "title"
+ url
* folder: N/A
* file: N/A
+ visible
* folder: "availability/available"
* file: "availability/available"
+ container
* folder: "folder" ? same as kvv
* file: "file" ? same as kvv
- Folder "resource/x-bb-folder"
+ https://lms.fu-berlin.de/learn/api/public/v1/courses/_127131_1/contents/_3602247_1/children
- File "resource/x-bb-document"
+ https://lms.fu-berlin.de/learn/api/public/v1/courses/_127131_1/contents/_3635282_1/attachments
+ text: "body"
- Attachment-Download
+ https://lms.fu-berlin.de/learn/api/public/v1/courses/_127131_1/contents/_3635282_1/attachments/_2838023_1/download

20
docs/kvvlogin_new.txt Normal file
View File

@@ -0,0 +1,20 @@
1= GET https://kvv.imp.fu-berlin.de/Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub-qa
-> Location-Header: https://identity.fu-berlin.de:9443/idp-fub-qa/profile/SAML2/Redirect/SSO?SAMLResponse=[SAMLResponse]&RelayState=[RelayState]
2= GET [Location-Header 1]
-> Set-Cookie: JSESSIONID=[JSESSION-FU]
-> Location: /idp-fub-qa/profile/SAML2/Redirect/SSO?execution=e1s1
3= GET [Location-Header 2]
+ Cookie: JSESSIONID=[JSESSION-FU]
4= POST [Location-Header 2]
+ Body: j_username=[USERNAME]&j_password=[PASSWORD]&_eventId_proceed=
+ Header: Content-Type: application/x-www-form-urlencoded
+ Cookie: JSESSIONID=[JSESSION-FU]
-> Set-Cookie: shib_idp_session=[SHIB-IDP-SESSION]
-> Body SAMLResponse-Input-value
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]
6= https://kvv.imp.fu-berlin.de/sakai-login-tool/container
+ Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
-> Set-Cookie: JSESSIONID: [JSESSION-KVV]

View File

@@ -17,12 +17,3 @@ org.gradle.jvmargs=-Xmx1536m
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
systemProp.http.proxyHost=proxy1-3.biotronik.int
systemProp.http.proxyPort=9090
systemProp.http.proxyUser=Sebastian%20Seedorf
systemProp.http.proxyPassword=1111ApoTheke
systemProp.https.proxyHost=proxy1-3.biotronik.int
systemProp.https.proxyPort=9090
systemProp.https.proxyUser=Sebastian%20Seedorf
systemProp.https.proxyPassword=1111ApoTheke

View File

@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip