10 Commits

Author SHA1 Message Date
Sebastian Seedorf
c4f849072f Untested 2020-12-06 19:49:16 +01:00
Sebastian Seedorf
e9e169ff49 Bug fixed and sync performance improvements 2019-10-31 23:31:36 +01:00
Sebastian Seedorf
58c727b527 Version 43 (1.6.4) 2019-10-28 23:35:05 +01:00
Joshua Priebsch
6ade7b1561 Merge remote-tracking branch 'origin/master' 2019-10-28 23:20:16 +01:00
Joshua Priebsch
0bd9a70415 editing the share textes 2019-10-28 23:18:43 +01:00
Sebastian Seedorf
98d04cb810 Resource Download Android 10 Compatibility 2019-10-28 22:20:44 +01:00
Sebastian Seedorf
22b42ff3f4 Implemented calendar integration 2019-10-28 18:56:12 +01:00
Sebastian Seedorf
e5d7d1faae Better offline access with bad network connection 2019-10-27 22:11:58 +01:00
Sebastian Seedorf
61cf9d6d48 Preference optimizations 2019-10-27 21:47:11 +01:00
Sebastian Seedorf
8abad827a7 Renamed variable 2019-10-24 15:35:02 +02:00
44 changed files with 1314 additions and 885 deletions

View File

@@ -7,8 +7,8 @@ android {
applicationId "de.sebse.fuplanner"
minSdkVersion 21
targetSdkVersion 29
versionCode 42
versionName "1.6.3"
versionCode 43
versionName "1.6.4"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="de.sebse.fuplanner">
<uses-permission
@@ -21,6 +22,10 @@
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<!-- Calendar integration -->
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<application
android:allowBackup="true"
android:fullBackupContent="@xml/backup_descriptor"
@@ -58,7 +63,6 @@
android:syncable="true">
</provider>
<activity
android:name=".services.fulogin.FUAuthenticatorActivity"
android:label="@string/title_activity_fuauthenticator" />

View File

@@ -278,17 +278,12 @@ public class MainActivity extends AppCompatActivity
updateNavigation();
if (restoreResult == Login.RESTORE_STATUS_SUCCESS && !isLoggedInBeforePause) {
changeFragment(getDefaultFragmentAfterLogin());
registerSync();
} else if (restoreResult == Login.RESTORE_STATUS_INVALID_PASSWORD && isLoggedInBeforePause) {
kvv.account().logout(false);
changeFragment(getDefaultFragmentAfterLogout());
}
});
kvv.modules().list().reloadIfOutdated();
});
}
isPaused = false;
if (restoreResult == Login.RESTORE_STATUS_SUCCESS || restoreResult == Login.RELOGIN) {
if (!Preferences.getBoolean(this, R.string.pref_set_auto_sync_on_startup) && mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
registerSync(true);
Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, true);
@@ -296,6 +291,12 @@ public class MainActivity extends AppCompatActivity
registerSync();
}
}
});
kvv.modules().list().reloadIfOutdated();
});
}
isPaused = false;
}
@Override
public void onBackPressed() {
@@ -545,6 +546,13 @@ public class MainActivity extends AppCompatActivity
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(this, R.array.pref_sync_frequency)) * 60 * 60
);
forceSync();
}
}
public void forceSync() {
Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null && ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME)) {
ContentResolver.requestSync(accountByType, KVVContentProvider.PROVIDER_NAME, Bundle.EMPTY);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -49,12 +49,11 @@ public class CanteenBrowser extends HTTPService {
}
public void getCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
queue.add("list", () -> {
if (this.canteens != null && !forceRefresh) {
callback.onResponse(this.canteens);
queue.next("list");
return;
}
queue.add("list", () -> {
this.upgradeCanteens(success -> {
if (this.canteens == null)
this.canteens = success;
@@ -111,12 +110,11 @@ public class CanteenBrowser extends HTTPService {
}
public void getAvailableCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
queue.add("available", () -> {
if (this.availableCanteens != null && !forceRefresh) {
callback.onResponse(this.availableCanteens);
queue.next("available");
return;
}
queue.add("available", () -> {
this.upgradeAvailableCanteens(success -> {
if (this.availableCanteens == null)
this.availableCanteens = success;
@@ -186,12 +184,11 @@ public class CanteenBrowser extends HTTPService {
public void getCanteen(Canteen canteen, final NetworkCallback<Canteen> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
String hash = "canteen" + canteen.getId();
queue.add(hash, () -> {
if (canteen.size() > 0 && !forceRefresh) {
callback.onResponse(canteen);
queue.next(hash);
return;
}
queue.add(hash, () -> {
this.upgradeCanteen(canteen, success -> {
canteen.update(success);
this.save();
@@ -233,12 +230,11 @@ public class CanteenBrowser extends HTTPService {
public void getDay(Day day, final NetworkCallback<Day> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
String hash = "day" + day.getCanteenId() + "@@@" + Canteen.calendarToKey(day.getCalendar());
queue.add(hash, () -> {
if (day.size() > 0 && !forceRefresh) {
callback.onResponse(day);
queue.next(hash);
return;
}
queue.add(hash, () -> {
this.upgradeDay(day, success -> {
day.update(success);
this.save();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -46,7 +46,7 @@ public class ModulesEvents extends PartModules<EventList> {
errorCallback.onError(new NetworkError(101404, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format(Constants.WB_SERVER_URL +"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101401, 403, "No events retrieved!"));

View File

@@ -6,8 +6,6 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import de.sebse.fuplanner.services.kvv.types.Grade;
import de.sebse.fuplanner.services.kvv.types.Gradebook;
import de.sebse.fuplanner.services.kvv.types.Modules;
@@ -39,7 +37,7 @@ public class ModulesGradebook extends PartModules<Gradebook> {
errorCallback.onError(new NetworkError(101504, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format(Constants.KVV_SERVER_URL+"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
super.get(String.format(Constants.WB_SERVER_URL +"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101501, 403, "No gradebook retrieved!"));

View File

@@ -104,9 +104,10 @@ public class ModulesList extends HTTPService {
} catch (FileNotFoundException ignored) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
delete();
}
if (this.mModules == null) {
recv(success -> {}, log::e);
recv(success -> {}, log::e, true);
}
}
@@ -131,6 +132,10 @@ public class ModulesList extends HTTPService {
mLogin.getLoginTokenBB() != null && mLogin.getLoginTokenBB().isOtherUser(mModules.getUsername())
)
delete();
if (this.mModules != null && !forceRefresh) {
callback.onResponse(this.mModules);
return;
}
mQueue.add(() -> {
if (mLogin.isLoginPending()) {
mLogin.restoreOnlineLogin(resCode -> {
@@ -141,11 +146,6 @@ public class ModulesList extends HTTPService {
}
});
mQueue.add(() -> {
if (this.mModules != null && !forceRefresh) {
callback.onResponse(this.mModules);
mQueue.next();
return;
}
Function<Integer, NetworkErrorCallback> errorFunc = ((Integer errorCode) -> (error -> {
if (retries > 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
mLogin.refreshLogin(success -> {
@@ -194,7 +194,7 @@ public class ModulesList extends HTTPService {
callback.onResponse(modules);
return;
}
get(Constants.KVV_SERVER_URL+"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
get(Constants.WB_SERVER_URL +"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101111, 403, "No membership list retrieved!"));
@@ -226,7 +226,7 @@ public class ModulesList extends HTTPService {
if (--latch[0] == 0) successCallback.onResponse(modules);
continue;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/site/%s.json?_validateSession=", courseId), mLogin.getLoginTokenKVV().getCookies(), response1 -> {
get(String.format(Constants.WB_SERVER_URL +"direct/site/%s.json?_validateSession=", courseId), mLogin.getLoginTokenKVV().getCookies(), response1 -> {
String body1 = response1.getParsed();
if (body1 == null) {
errorCallback.onError(new NetworkError(101113, 403, "No site retrieved!"));

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;
@@ -46,7 +47,7 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format(Constants.WB_SERVER_URL +"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101601, 403, "No resources retrieved!"));
@@ -367,8 +368,15 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
}
private String saveFileInDownloads(String filename, byte[] data, String moduleName) {
// Saves file in folder: DOWNLOADS/moduleName
File folder = new File(Environment.getExternalStoragePublicDirectory(
File folder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
folder = new File(getContext().getExternalFilesDir(
Environment.DIRECTORY_DOWNLOADS), moduleName);
} else {
folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), moduleName);
}
if (!folder.mkdirs()) {
log.w( "Directory not created");
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -82,8 +82,8 @@ public class CacheBBCourse implements Serializable {
return mKVVCourseList.contains(courseID);
}
public void setBBCourse(String courseID, Modules.Module lecturer) {
mBBCourseList.put(courseID, lecturer);
public void setBBCourse(String courseID, Modules.Module module) {
mBBCourseList.put(courseID, module);
mBBCourseListRefresh.put(courseID, System.currentTimeMillis());
}

View File

@@ -68,8 +68,8 @@ public class CacheKVVCourse implements Serializable {
fos.close();
}
public void setKVVCourse(String courseID, Modules.Module lecturer) {
mKVVCourseList.put(courseID, lecturer);
public void setKVVCourse(String courseID, Modules.Module module) {
mKVVCourseList.put(courseID, module);
mKVVCourseListRefresh.put(courseID, System.currentTimeMillis());
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,11 +2,13 @@ package de.sebse.fuplanner.services.kvv.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import java.io.File;
@@ -47,8 +49,14 @@ public class Download {
if (context == null)
return;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
File f = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+"/"+folderName+"/"+file.getTitle());
File f;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
f = new File(context.getExternalFilesDir(
Environment.DIRECTORY_DOWNLOADS) + "/" + folderName + "/" + file.getTitle());
} else {
f = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/" + folderName + "/" + file.getTitle());
}
Resources resources = context.getResources();
String message = "";
if (file.getAuthor() != null && !file.getAuthor().isEmpty())
@@ -236,7 +244,12 @@ public class Download {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
log.e("No matching activity found!");
e.printStackTrace();
}
}

View File

@@ -24,4 +24,6 @@ public interface MainActivityListener {
void addRequestPermissionsResultListener(RequestPermissionsResultListener listener, String id);
void removeRequestPermissionsResultListener(String id);
void forceSync();
}

View File

@@ -31,7 +31,7 @@
<string name="current_percentage">Punkte: %1$.1f / %2$.1f\nProzentsatz: %3$.1f \%%\nBeste Note: %4$.1f / %5$.1f - %6$.1f \%% (%7$s)</string>
<string name="offline_mode">Offline-Modus</string>
<string name="refresh_failed">Aktualisieren fehlgeschlagen…</string>
<string name="share_intent">Hey, schau\' dir die neue KVV App an: %1$s</string>
<string name="share_intent">Hey, schau dir die neue App für Whiteboard und Blackboard an der FU an: %1$s</string>
<string name="refresh">"Aktualisieren"</string>
<string name="go_to_today">Heute</string>
<string name="canteens">Kantinen</string>
@@ -52,6 +52,8 @@
<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="pref_add_calendar_title">Zum Kalender hinzufügen</string>
<string name="pref_add_calendar_summary">Wenn ausgewählt, wird </string>
<string name="meals">Hauptgerichte</string>
<string name="special_meals">Spezial Gerichte</string>
<string name="side_dishes">Beilagen</string>

View File

@@ -1,54 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="pref_price_group_entries">
<item>All</item>
<item>Student</item>
<item>Employee</item>
<item>Other</item>
</string-array>
<string-array name="pref_price_group_values" translatable="false">
<item>all</item>
<item>student</item>
<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>
<string-array name="pref_food_level_entries">
<item>Show every meal</item>
<item>Show only vegetarian meals</item>
<item>Show only vegan meals</item>
</string-array>
<string-array name="pref_food_level_values" translatable="false">
<item>all</item>
<item>vegetarian</item>
<item>vegan</item>
</string-array>
<string-array name="pref_night_mode_entries">
<item>Follow system default</item>
<item>Always day mode</item>
<item>Always night mode</item>
</string-array>
<string-array name="pref_night_mode_values" translatable="false">
<item>auto</item>
<item>day</item>
<item>night</item>
</string-array>
</resources>

View File

@@ -1,6 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Select an item -->
<string-array name="pref_price_group_entries">
<item>All</item>
<item>Student</item>
<item>Employee</item>
<item>Other</item>
</string-array>
<string-array name="pref_price_group_values" translatable="false">
<item>all</item>
<item>student</item>
<item>employee</item>
<item>other</item>
</string-array>
<string-array name="pref_price_group" translatable="false">
<item>@string/pref_price_group</item>
<item>@string/pref_price_group_default</item>
@@ -8,6 +20,22 @@
<string name="pref_price_group" translatable="false">pref_price_group</string>
<string name="pref_price_group_default" translatable="false">all</string>
<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>
<string-array name="pref_sync_frequency" translatable="false">
<item>@string/pref_sync_frequency</item>
<item>@string/pref_sync_frequency_default</item>
@@ -15,6 +43,16 @@
<string name="pref_sync_frequency" translatable="false">pref_sync_frequency</string>
<string name="pref_sync_frequency_default" translatable="false">6</string>
<string-array name="pref_food_level_entries">
<item>Show every meal</item>
<item>Show only vegetarian meals</item>
<item>Show only vegan meals</item>
</string-array>
<string-array name="pref_food_level_values" translatable="false">
<item>all</item>
<item>vegetarian</item>
<item>vegan</item>
</string-array>
<string-array name="pref_food_level" translatable="false">
<item>@string/pref_food_level</item>
<item>@string/pref_food_level_default</item>
@@ -22,6 +60,16 @@
<string name="pref_food_level" translatable="false">pref_food_level</string>
<string name="pref_food_level_default" translatable="false">all</string>
<string-array name="pref_night_mode_entries">
<item>Follow system default</item>
<item>Always day mode</item>
<item>Always night mode</item>
</string-array>
<string-array name="pref_night_mode_values" translatable="false">
<item>auto</item>
<item>day</item>
<item>night</item>
</string-array>
<string-array name="pref_night_mode" translatable="false">
<item>@string/pref_night_mode</item>
<item>@string/pref_night_mode_default</item>
@@ -29,6 +77,9 @@
<string name="pref_night_mode" translatable="false">pref_night_mode</string>
<string name="pref_night_mode_default" translatable="false">auto</string>
<string name="pref_add_calendar" translatable="false">pref_add_calendar</string>
<string name="pref_add_calendar_default" translatable="false">false</string>
<!-- Other preferences -->
<string name="pref_last_visited_news" translatable="false">pref_last_visited_news</string>

View File

@@ -11,7 +11,7 @@
<string name="schedule">Schedule</string>
<string name="courses">Courses</string>
<string name="canteen_plan">Canteen Plan</string>
<string name="settings">Settings</string>
<string name="settings">Preferences</string>
<string name="options">Options</string>
<string name="log_out">Log out</string>
<string name="share">Share</string>
@@ -33,7 +33,7 @@
<string name="current_percentage">Points: %1$.1f / %2$.1f\nPercentage: %3$.1f \%%\nBest Grade: %4$.1f / %5$.1f - %6$.1f \%% (%7$s)</string>
<string name="offline_mode">Offline Mode</string>
<string name="refresh_failed">Refresh failed…</string>
<string name="share_intent">Hey, check out the new KVV app: %1$s</string>
<string name="share_intent">Hey, check out the new Whiteboard and Blackboard app: %1$s</string>
<string name="app_url" translatable="false">https://play.google.com/store/apps/details?id=de.sebse.fuplanner</string>
<string name="refresh">Refresh</string>
<string name="go_to_today">Go to today</string>
@@ -59,6 +59,8 @@
<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="pref_add_calendar_title">Add to Calendar</string>
<string name="pref_add_calendar_summary">If checked schedule will be added to your calendar app</string>
<string name="meals">Meals</string>
<string name="special_meals">Special meals</string>
<string name="side_dishes">Side Dishes</string>

View File

@@ -33,6 +33,11 @@
android:entries="@array/pref_sync_frequency_entries"
android:entryValues="@array/pref_sync_frequency_values"
android:dialogTitle="@string/pref_sync_frequency_dialog" />
<CheckBoxPreference
android:key="@string/pref_add_calendar"
android:defaultValue="@string/pref_add_calendar_default"
android:title="@string/pref_add_calendar_title"
android:summary="@string/pref_add_calendar_summary" />
<PreferenceScreen
android:title="@string/open_data_policy"
android:summary="@string/open_data_policy_summary">