3 Commits

Author SHA1 Message Date
Caesar2011
6325f312ea unfinished code 2019-01-07 13:25:24 +01:00
Caesar2011
e0ed23dec5 Still unfinished JSON converter 2019-01-04 15:02:07 +01:00
Caesar2011
bb85911324 Unfinished, unusable code 2019-01-04 00:06:11 +01:00
102 changed files with 1631 additions and 4198 deletions

View File

@@ -7,8 +7,8 @@ android {
applicationId "de.sebse.fuplanner"
minSdkVersion 15
targetSdkVersion 28
versionCode 39
versionName "1.5.16_2"
versionCode 16
versionName "1.3.5"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
@@ -27,15 +27,28 @@ android {
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0-beta02', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'androidx.preference:preference:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.github.Cutta:TagView:1.3'
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.google.android.gms:play-services-base:16.1.0'
implementation 'com.ms-square:expandableTextView:0.1.4'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2'
implementation 'com.android.volley:volley:1.1.0'
//noinspection GradleDependency
implementation 'com.google.android.gms:play-services-auth:15.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'org.jetbrains:annotations-java5:15.0'
//implementation 'com.github.quivr:android-week-view:2.0.2' //com.github.alamkanak:android-week-view:1.2.6
//implementation 'com.github.quivr:android-week-view:2.0.2'//com.github.alamkanak:android-week-view:1.2.6
implementation 'com.ms-square:expandableTextView:0.1.4'
// https://github.com/bignerdranch/expandable-recycler-view
implementation 'com.bignerdranch.android:expandablerecyclerview:3.0.0-RC1'
implementation 'com.github.Cutta:TagView:1.3'
implementation files('libs/jericho-html-3.4.jar')
}

View File

@@ -0,0 +1,27 @@
package de.sebse.fuplanner;
import android.content.Context;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("de.sebse.fuplanner", appContext.getPackageName());
}
}

View File

@@ -18,6 +18,8 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
@@ -31,9 +33,7 @@
android:theme="@style/FUTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:clearTaskOnLaunch="true"
android:launchMode="singleTop">
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.MAIN" />
@@ -80,20 +80,6 @@
android:name="android.content.SyncAdapter"
android:resource="@xml/syncadapter_kvv" />
</service>
<service
android:name=".services.kvv.KVV"
android:exported="false">
<intent-filter>
<action android:name="android.app.Service" />
</intent-filter>
</service>
<service
android:name=".tools.network.HTTPNetwork"
android:exported="false">
<intent-filter>
<action android:name="android.app.Service" />
</intent-filter>
</service>
</application>

View File

@@ -1,15 +1,8 @@
package de.sebse.fuplanner;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@@ -21,15 +14,12 @@ import com.google.android.material.navigation.NavigationView;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.arch.core.util.Function;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
@@ -49,17 +39,13 @@ import de.sebse.fuplanner.fragments.moddetails.ModDetailFragment;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.CanteenListener;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.kvv.Login;
import de.sebse.fuplanner.services.kvv.sync.KVVContentProvider;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.news.NewsManager;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.CustomNotificationManager;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.Preferences;
@@ -74,58 +60,27 @@ public class MainActivity extends AppCompatActivity
ModulesFragment.OnModulesFragmentInteractionListener,
CanteensFragment.OnCanteensFragmentInteractionListener {
public static final int FRAGMENT_NONE = -1;
public static final int FRAGMENT_STARTUP = 0;
public static final int FRAGMENT_MODULES = 1;
public static final int FRAGMENT_MODULES_DETAILS = 2;
public static final int FRAGMENT_SCHEDULE = 4;
public static final int FRAGMENT_CANTEENS = 5;
public static final int FRAGMENT_CANTEENS_DETAILS = 6;
public static final int FRAGMENT_PREFERENCES = 7;
public static final int FRAGMENT_NEWS = 8;
private static final int FRAGMENT_NONE = -1;
private static final int FRAGMENT_STARTUP = 0;
private static final int FRAGMENT_MODULES = 1;
private static final int FRAGMENT_MODULES_DETAILS = 2;
private static final int FRAGMENT_SCHEDULE = 4;
private static final int FRAGMENT_CANTEENS = 5;
private static final int FRAGMENT_CANTEENS_DETAILS = 6;
private static final int FRAGMENT_PREFERENCES = 7;
private static final int FRAGMENT_NEWS = 8;
private static final String ARG_FRAGMENT_PAGE = "fragment_page";
private static final String ARG_FRAGMENT_STATUS = "fragment_status";
private static final int DOUBLE_CLICK_TO_EXIT_MILLIS = 2000;
private FragmentManager mFragmentManager;
private KVV mKVV;
private NewsManager mNewsManager;
private CanteenBrowser mCanteenBrowser;
private final Logger log = new Logger(this);
private NavigationView mNavigationView;
private boolean mAlreadyCreated = false;
// KVV service
private ArrayList<KVVCallback> mCallbacks = new ArrayList<>();
@Nullable private KVV mKVV;
boolean mBound = false;
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
KVV.LocalBinder binder = (KVV.LocalBinder) service;
mKVV = binder.getService();
mKVV.addListener("mainactivity", MainActivity.this);
for (KVVCallback callback : mCallbacks) {
callback.get(mKVV);
}
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mKVV.removeListener("mainactivity");
mBound = false;
mKVV = null;
}
};
private int mFragmentPage = FRAGMENT_NONE;
@NotNull
private String mFragmentData = "";
@@ -135,24 +90,14 @@ public class MainActivity extends AppCompatActivity
private CustomAccountManager mAccountManager;
private boolean isPaused = false;
private boolean isLoggedInBeforePause = false;
private boolean isDrawerFixed = false;
private Function<Modules, Void> mMolduleListUpdateFunction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAccountManager = new CustomAccountManager(AccountManager.get(this), () -> MainActivity.this);
isDrawerFixed = getResources().getBoolean(R.bool.isDrawerFixed);
int desiredPage = getDefaultFragmentAfterLogin();
String desiredData = "";
Intent intent = getIntent();
if (intent != null && CustomNotificationManager.NOTIFICATION_TYPE_NAVIGATE.equals(intent.getStringExtra(CustomNotificationManager.NOTIFICATION_INTENT))) {
int page = intent.getIntExtra(CustomNotificationManager.NOTIFICATION_PAGE, 0);
if (page == FRAGMENT_STARTUP || page == FRAGMENT_NONE)
page = getDefaultFragmentAfterLogin();
desiredPage = page;
desiredData = intent.getStringExtra(CustomNotificationManager.NOTIFICATION_DATA);
} else if (savedInstanceState != null) {
if (savedInstanceState != null) {
desiredPage = savedInstanceState.getInt(ARG_FRAGMENT_PAGE, desiredPage);
desiredData = savedInstanceState.getString(ARG_FRAGMENT_STATUS, desiredData);
}
@@ -161,13 +106,11 @@ public class MainActivity extends AppCompatActivity
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (!isDrawerFixed) {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
mNavigationView = findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);
@@ -177,7 +120,7 @@ public class MainActivity extends AppCompatActivity
if (!mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
desiredPage = getDefaultFragmentAfterLogout();
desiredData = "";
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
updateNavigation();
changeFragment(desiredPage, desiredData);
} else {
@@ -185,95 +128,35 @@ public class MainActivity extends AppCompatActivity
changeFragment(FRAGMENT_STARTUP);
int targetPage = desiredPage;
String targetData = desiredData;
getKVV(kvv -> {
kvv.account().restoreOnlineLogin(restoreResult -> {
updateNavigation();
if (restoreResult != Login.RESTORE_STATUS_INVALID_PASSWORD)
changeFragment(targetPage, targetData);
else
changeFragment(getDefaultFragmentAfterLogout());
});
getKVV().account().restoreOnlineLogin(isRestored -> {
updateNavigation();
if (isRestored)
changeFragment(targetPage, targetData);
else
changeFragment(getDefaultFragmentAfterLogout());
});
}
if (!mAlreadyCreated) {
Intent serviceIntent = new Intent(this, KVV.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
mAlreadyCreated = true;
if (!Preferences.getBoolean(this, R.string.pref_set_auto_sync_on_startup)) {
registerSync(true);
Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, true);
} else {
registerSync(false);
}
CustomNotificationManager.createNotificationChannel(this);
/*getKVV(kvv -> {
kvv.modules().list().recv(list -> {
Modules.Module module = list.getByIndex(0);
CustomNotificationManager.sendNotification(this, "Test", module.title, FRAGMENT_MODULES_DETAILS, module.getID()+"."+ ModulePart.getPageByPart(ModulePart.EVENT));
}, log::e);
});*/
}
@Override
protected void onStart() {
super.onStart();
if (!mAlreadyCreated) {
Intent serviceIntent = new Intent(this, KVV.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
mAlreadyCreated = true;
}
@Override
protected void onStop() {
super.onStop();
if (mKVV != null)
mKVV.removeListener("mainactivity");
if (mBound)
unbindService(mConnection);
mKVV = null;
mBound = false;
mAlreadyCreated = false;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (CustomNotificationManager.NOTIFICATION_TYPE_NAVIGATE.equals(intent.getStringExtra(CustomNotificationManager.NOTIFICATION_INTENT))) {
int page = intent.getIntExtra(CustomNotificationManager.NOTIFICATION_PAGE, 0);
String data = intent.getStringExtra(CustomNotificationManager.NOTIFICATION_DATA);
if (page == FRAGMENT_STARTUP || page == FRAGMENT_NONE)
page = getDefaultFragmentAfterLogin();
changeFragment(page, data);
}
}
@Override
protected void onPause() {
super.onPause();
isPaused = true;
getKVV(kvv -> isLoggedInBeforePause = kvv.account().isLoggedIn());
isLoggedInBeforePause = getKVV().account().isLoggedIn();
}
@Override
protected void onResume() {
super.onResume();
if (isPaused) {
getKVV(kvv -> {
kvv.account().restoreOnlineLogin(restoreResult -> {
updateNavigation();
if (restoreResult == Login.RESTORE_STATUS_SUCCESS && !isLoggedInBeforePause) {
changeFragment(getDefaultFragmentAfterLogin());
registerSync(true);
} else if (restoreResult == Login.RESTORE_STATUS_INVALID_PASSWORD && isLoggedInBeforePause) {
kvv.account().logout(false);
changeFragment(getDefaultFragmentAfterLogout());
}
});
kvv.modules().list().reloadIfOutdated();
getKVV().account().restoreOnlineLogin(isRestored -> {
updateNavigation();
if (isRestored && !isLoggedInBeforePause)
changeFragment(getDefaultFragmentAfterLogin());
else if (!isRestored && isLoggedInBeforePause) {
getKVV().account().logout(false);
changeFragment(getDefaultFragmentAfterLogout());
}
});
}
isPaused = false;
@@ -287,32 +170,30 @@ public class MainActivity extends AppCompatActivity
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
getKVV(kvv -> {
if (mFragmentPage == FRAGMENT_MODULES_DETAILS) {
ModDetailFragment fragment = (ModDetailFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_MODULES_DETAILS));
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
fragment.gotoFragmentPart(0, -1);
} else {
changeFragment(FRAGMENT_MODULES);
}
} else if (mFragmentPage == FRAGMENT_CANTEENS_DETAILS) {
DaySwitcherFragment fragment = (DaySwitcherFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS_DETAILS));
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
fragment.gotoFragmentPart(0);
} else {
changeFragment(FRAGMENT_CANTEENS);
}
} else if (kvv.account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
changeFragment(getDefaultFragmentAfterLogin());
if (mFragmentPage == FRAGMENT_MODULES_DETAILS) {
ModDetailFragment fragment = (ModDetailFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_MODULES_DETAILS));
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
fragment.gotoFragmentPart(0, -1);
} else {
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
showToast(R.string.back_to_exit);
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD);
changeFragment(FRAGMENT_MODULES);
}
});
} else if (mFragmentPage == FRAGMENT_CANTEENS_DETAILS) {
DaySwitcherFragment fragment = (DaySwitcherFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS_DETAILS));
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
fragment.gotoFragmentPart(0);
} else {
changeFragment(FRAGMENT_CANTEENS);
}
} else if (getKVV().account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
changeFragment(getDefaultFragmentAfterLogin());
} else {
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
showToast(R.string.back_to_exit);
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV);
}
}
}
@@ -379,17 +260,13 @@ public class MainActivity extends AppCompatActivity
startActivity(sendIntent);
break;
case R.id.nav_logout:
getKVV(kvv -> {
kvv.account().logout(true);
kvv.modules().list().delete();
});
getKVV().account().logout(true);
getKVV().modules().list().delete();
break;
}
if (!isDrawerFixed) {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
int size = mNavigationView.getMenu().size();
for (int k = 0; k < size; k++) {
@@ -434,12 +311,11 @@ public class MainActivity extends AppCompatActivity
return this.mNewsManager;
}
public void getKVV(KVVCallback callback) {
public KVV getKVV() {
if (this.mKVV == null) {
mCallbacks.add(callback);
} else {
callback.get(this.mKVV);
this.mKVV = new KVV(this, this);
}
return this.mKVV;
}
public CanteenBrowser getCanteenBrowser() {
@@ -461,7 +337,7 @@ public class MainActivity extends AppCompatActivity
setRefreshFailedBanner(false);
updateNavigation();
changeFragment(getDefaultFragmentAfterLogout());
//mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
}
private void toLoginState(String fullName, String email, int newFragment) {
@@ -474,19 +350,6 @@ public class MainActivity extends AppCompatActivity
changeFragment(newFragment);
}
private void registerSync(boolean onLogin) {
Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null) {
if (onLogin)
ContentResolver.setSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME, true);
ContentResolver.addPeriodicSync(
accountByType,
KVVContentProvider.PROVIDER_NAME,
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(this, R.array.pref_sync_frequency))*60*60);
}
}
private void changeFragment(int newFragment) {
changeFragment(newFragment, "");
}
@@ -508,6 +371,9 @@ public class MainActivity extends AppCompatActivity
case FRAGMENT_MODULES:
fragment = ModulesFragment.newInstance();
break;
/*case FRAGMENT_LOGIN:
fragment = LoginFragment.newInstance();
break;*/
case FRAGMENT_SCHEDULE:
fragment = ScheduleFragment.newInstance();
break;
@@ -556,27 +422,20 @@ public class MainActivity extends AppCompatActivity
private void setNavigationSelection() {
MenuItem item = null;
int dotPos = mFragmentData.indexOf(".");
String moduleId = mFragmentData;
if (dotPos != -1)
moduleId = moduleId.substring(0, dotPos);
switch (mFragmentPage) {
case FRAGMENT_MODULES_DETAILS:
String finalModuleId = moduleId;
getKVV(kvv -> {
kvv.modules().list().find(finalModuleId, success -> {
int size = mNavigationView.getMenu().size();
//noinspection ConstantConditions
String title = success == null ? null : success.title;
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
}
getKVV().modules().list().find(mFragmentData, success -> {
int size = mNavigationView.getMenu().size();
//noinspection ConstantConditions
String title = success == null ? null : success.title;
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
}
}, log::e);
});
}
}, log::e);
return;
case FRAGMENT_MODULES:
item = mNavigationView.getMenu().findItem(R.id.nav_modules);
@@ -587,19 +446,15 @@ public class MainActivity extends AppCompatActivity
case FRAGMENT_CANTEENS_DETAILS:
getCanteenBrowser().getCanteens(success -> {
int size = mNavigationView.getMenu().size();
try {
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
//noinspection ConstantConditions
String title = canteen == null ? null : canteen.getName();
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
}
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
//noinspection ConstantConditions
String title = canteen == null ? null : canteen.getName();
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
if (menuItem.getTitle().equals(title)) {
menuItem.setChecked(true);
break;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}, log::e);
return;
@@ -631,10 +486,10 @@ public class MainActivity extends AppCompatActivity
if (!viewBtn.hasOnClickListeners())
viewBtn.setOnClickListener(v -> {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
});
}
@@ -642,23 +497,21 @@ public class MainActivity extends AppCompatActivity
int MAX_COUNT = isLoggedIn ? 3 : 2;
final int[] count = {0};
if (isLoggedIn) {
getKVV(kvv -> {
kvv.modules().list().recv(success -> {
int i = 0;
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
Modules.Module module = it.next();
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
menuItem.setOnMenuItemClickListener(item -> {
onModulesFragmentInteraction(module.getID());
return false;
});
i++;
}
if (++count[0] == MAX_COUNT) done.run();
}, error -> {
if (++count[0] == MAX_COUNT) done.run();
log.e(error);
});
getKVV().modules().list().recv(success -> {
int i = 0;
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
Modules.Module module = it.next();
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
menuItem.setOnMenuItemClickListener(item -> {
onModulesFragmentInteraction(module.getID());
return false;
});
i++;
}
if (++count[0] == MAX_COUNT) done.run();
}, error -> {
if (++count[0] == MAX_COUNT) done.run();
log.e(error);
});
}
getCanteenBrowser().getCanteens(success -> {
@@ -699,18 +552,16 @@ public class MainActivity extends AppCompatActivity
private void updateNavigation() {
mQueue.add(() -> {
getKVV(kvv -> {
boolean isLoggedIn = kvv.account().isLoggedIn();
setNavigationHeader(isLoggedIn);
mNavigationView.getMenu().clear();
if (isLoggedIn)
mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
else
mNavigationView.inflateMenu(R.menu.activity_main_drawer);
afterAnyMenuInflate(isLoggedIn, () -> {
setNavigationSelection();
mQueue.next();
});
boolean isLoggedIn = getKVV().account().isLoggedIn();
setNavigationHeader(isLoggedIn);
mNavigationView.getMenu().clear();
if (isLoggedIn)
mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
else
mNavigationView.inflateMenu(R.menu.activity_main_drawer);
afterAnyMenuInflate(isLoggedIn, () -> {
setNavigationSelection();
mQueue.next();
});
});
}
@@ -732,11 +583,6 @@ public class MainActivity extends AppCompatActivity
setNavigationSelection();
}
@Override
public void onModulesFragmentListUpdate(Function<Modules, Void> update) {
this.mMolduleListUpdateFunction = update;
}
@Override
public void onCanteensFragmentInteraction(final int itemID) {
changeFragment(FRAGMENT_CANTEENS_DETAILS, String.valueOf(itemID));
@@ -789,21 +635,8 @@ public class MainActivity extends AppCompatActivity
@Override
public void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {
String fullName = "";
if (tokenKVV != null && !TextUtils.isEmpty(tokenKVV.getFullName())) {
fullName = tokenKVV.getFullName();
} else if (tokenBB != null && !TextUtils.isEmpty(tokenBB.getUsername())) {
fullName = tokenBB.getUsername();
}
String email = "";
if (tokenKVV != null && !TextUtils.isEmpty(tokenKVV.getEmail()) && !"null".equals(tokenKVV.getEmail())) {
email = tokenKVV.getEmail();
} else if (tokenBB != null && !TextUtils.isEmpty(tokenBB.getUsername())) {
email = tokenBB.getUsername() + "@zedat.fu-berlin.de";
}
toLoginState(fullName, email, getDefaultFragmentAfterLogin());
public void onLogin(LoginToken token) {
toLoginState(token.getFullName(), token.getEmail(), getDefaultFragmentAfterLogin());
}
@Override
@@ -825,15 +658,4 @@ public class MainActivity extends AppCompatActivity
public CustomAccountManager getAccountManager() {
return mAccountManager;
}
public interface KVVCallback {
void get(KVV kvv);
}
@Override
public void onModuleListPartiallyUpdated(Modules modules) {
if (mMolduleListUpdateFunction != null) {
mMolduleListUpdateFunction.apply(modules);
}
}
}

View File

@@ -40,10 +40,12 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
public void setModules(Modules modules) {
mValues = modules;
mPositionalData.clear();
Semester lastSemester = new Semester(Semester.SEM_WS, 0);
Semester lastSemester = null;
for (Modules.Module module : mValues) {
Semester semester = module.semester;
if (semester != null && !semester.equals(lastSemester) || semester == null && lastSemester != null) {
if (semester == null)
continue;
if (!semester.equals(lastSemester)) {
mPositionalData.add(new Pair<>(TYPE_HEADER, semester));
lastSemester = semester;
}
@@ -78,9 +80,7 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
StringViewHolder sHolder = (StringViewHolder) holder;
String localizedSemester;
Semester semester = (Semester) pair.second;
if (semester == null)
localizedSemester = holder.mView.getResources().getString(R.string.others);
else if (semester.getType() == Semester.SEM_WS)
if (semester.getType() == Semester.SEM_WS)
localizedSemester = holder.mView.getResources().getString(R.string.winter_semester, semester.getYear(), semester.getYear()+1);
else
localizedSemester = holder.mView.getResources().getString(R.string.summer_semester, semester.getYear());

View File

@@ -8,13 +8,11 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.arch.core.util.Function;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;
@@ -68,15 +66,15 @@ public class ModulesFragment extends Fragment {
private void refresh(boolean forceRefresh) {
if (mMainActivityListener != null) {
mMainActivityListener.getKVV(kvv -> {
kvv.modules().list().recv(success -> {
adapter.setModules(success);
swipeLayout.setRefreshing(false);
}, error -> {
log.e(error.toString());
swipeLayout.setRefreshing(false);
}, forceRefresh);
});
mMainActivityListener.getKVV().modules().list().recv(success -> {
adapter.setModules(success);
//if (mMainActivityListener != null)
// mMainActivityListener.refreshNavigation();
swipeLayout.setRefreshing(false);
}, error -> {
log.e(error.toString());
swipeLayout.setRefreshing(false);
}, forceRefresh);
}
}
@@ -86,10 +84,6 @@ public class ModulesFragment extends Fragment {
super.onAttach(context);
if (context instanceof OnModulesFragmentInteractionListener) {
mListener = (OnModulesFragmentInteractionListener) context;
mListener.onModulesFragmentListUpdate(modules -> {
if (adapter != null) adapter.setModules(modules);
return null;
});
} else {
throw new RuntimeException(context.toString()
+ " must implement OnModulesFragmentInteractionListener");
@@ -111,6 +105,5 @@ public class ModulesFragment extends Fragment {
public interface OnModulesFragmentInteractionListener {
void onModulesFragmentInteraction(String id);
void onModulesFragmentListUpdate(Function<Modules, Void> update);
}
}

View File

@@ -1,22 +1,18 @@
package de.sebse.fuplanner.fragments;
import android.accounts.Account;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.sync.KVVContentProvider;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.logging.Logger;
public class PrefsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
private Logger log = new Logger(this);
public static PrefsFragment newInstance() {
PrefsFragment fragment = new PrefsFragment();
Bundle args = new Bundle();
@@ -50,20 +46,5 @@ public class PrefsFragment extends PreferenceFragmentCompat implements SharedPre
Preference preference = getPreferenceScreen().findPreference(s);
if (preference instanceof ListPreference)
preference.setSummary(((ListPreference) preference).getEntry());
if (getActivity() != null && getActivity() instanceof MainActivity) {
CustomAccountManager accountManager = ((MainActivity) getActivity()).getAccountManager();
if (accountManager != null) {
Account accountByType = accountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null) {
ContentResolver.setSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME, true);
ContentResolver.addPeriodicSync(
accountByType,
KVVContentProvider.PROVIDER_NAME,
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(getActivity(), R.array.pref_sync_frequency)));
}
}
}
}
}

View File

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

View File

@@ -56,7 +56,7 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Meal meal = getMeal(position);
viewHolder.mTitle.setText(meal.getName());
String value;
switch (Preferences.getStringArray(mContext, R.array.pref_price_group)) {
switch (Preferences.getString(mContext, R.array.pref_price_group)) {
case "student":
if (meal.getPriceStdnt() < 0)
value = mContext.getResources().getString(R.string.no_price_available);

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,9 +1,7 @@
package de.sebse.fuplanner.fragments.moddetails;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
@@ -21,6 +19,7 @@ import de.sebse.fuplanner.services.kvv.types.EventList;
import de.sebse.fuplanner.services.kvv.types.GroupedEvents;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
import de.sebse.fuplanner.tools.ui.StringViewHolder;
@@ -42,6 +41,8 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private Modules.Module mValue;
private final ArrayList<Pair<Integer, Object>> mPositionalData;
private final Logger log = new Logger(this);
ModDetailEventAdapter() {
mValue = null;
mPositionalData = new ArrayList<>();
@@ -80,20 +81,19 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
for (Map.Entry<String, GroupedEvents> value: listsGrouped.entrySet()) {
if (value.getValue().getGroups().size() > 0) {
mPositionalData.add(new Pair<>(TYPE_HEADER, value.getKey()));
ArrayList<GroupedEvents.Group> ungroupedGroups = new ArrayList<>();
for (GroupedEvents.Group group: value.getValue().getGroups()) {
boolean showAsGrouped = true;
if (group.getSkippedDates().size() > 3 || group.size() < 3) {
boolean showAsGrouped = true;
for (GroupedEvents.Group group : value.getValue().getGroups()) {
if (group.getSkippedDates().size() > 2) {
showAsGrouped = false;
}
if (showAsGrouped) {
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
} else {
ungroupedGroups.add(group);
break;
}
}
for (GroupedEvents.Group ungroupedGroup : ungroupedGroups) {
for (Event event: ungroupedGroup) {
if (showAsGrouped) {
for (GroupedEvents.Group group : value.getValue().getGroups()) {
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
}
} else {
for (Event event : value.getValue()) {
mPositionalData.add(new Pair<>(TYPE_UNGROUPED, event));
}
}
@@ -178,7 +178,7 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
end = UtilsDate.getModifiedDate(lastDateTime);
weekday = UtilsDate.getModifiedDate(context, firstDateTime, "E");
startTime = UtilsDate.getModifiedTime(context, firstDateTime);
endTime = UtilsDate.getModifiedTime(context, lastDateTime+1);
endTime = UtilsDate.getModifiedTime(context, lastDateTime);
for (long skippedDate : group.getSkippedDates()) {
if (excepts == null) {
excepts = new StringBuilder(UtilsDate.getModifiedDate(skippedDate));
@@ -186,30 +186,9 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
excepts.append(", ").append(UtilsDate.getModifiedDate(skippedDate));
}
}
String groupTitle = context.getString(R.string.event_scale, weekday, startTime, endTime);
if (!TextUtils.isEmpty(group.getTitle()) && !group.getTitle().equals(mValue.title))
groupTitle += " ("+group.getTitle()+")";
ig.mTitle.setText(groupTitle);
ig.mTitle.setText(context.getString(R.string.event_scale, weekday, startTime, endTime));
ig.mSubLeft.setText(context.getString(R.string.date_scale, start, end));
ig.mSubRight.setText(excepts != null ? context.getString(R.string.except_list, excepts.toString()) : "");
String moduleName = mValue.title;
StringBuilder finalExcepts = excepts;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ig.mView.getContext());
ig.mView.setOnClickListener(v -> {
alertDialogBuilder
.setTitle(R.string.events)
.setMessage(
ig.mView.getResources().getString(R.string.module_name, moduleName) + "\n" +
ig.mView.getResources().getString(R.string.location_name, group.getLocation()) + "\n" +
context.getString(R.string.event_scale, weekday, startTime, endTime) + "\n" +
context.getString(R.string.date_scale, start, end) + "\n" +
(finalExcepts != null ? context.getString(R.string.except_list, finalExcepts.toString()) : "")
)
.setCancelable(true)
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
});
return;
case TYPE_UNGROUPED:
ItemViewHolder iu = (ItemViewHolder) holder;
@@ -220,29 +199,13 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
else
start = UtilsDate.getModifiedDateTime(context, event.getStartDate());
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
end = UtilsDate.getModifiedTime(context, event.getEndDate()+1);
end = UtilsDate.getModifiedTime(context, event.getEndDate());
else
end = UtilsDate.getModifiedDateTime(context, event.getEndDate()+1);
end = UtilsDate.getModifiedDateTime(context, event.getEndDate());
date = context.getString(R.string.date_scale, start, end);
iu.mTitle.setText(event.getTitle());
iu.mSubLeft.setText(date);
iu.mSubRight.setText(event.getLocation());
String moduleName1 = mValue.title;
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(iu.mView.getContext());
iu.mView.setOnClickListener(v -> {
alertDialogBuilder1
.setTitle(moduleName1)
.setMessage(
iu.mView.getResources().getString(R.string.module_name, moduleName1) + "\n" +
iu.mView.getResources().getString(R.string.location_name, event.getLocation()) + "\n" +
date
)
.setCancelable(true)
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
});
iu.mSubRight.setText("");
}
}

View File

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

View File

@@ -72,13 +72,11 @@ public class ModDetailFragment extends Fragment implements ModDetailListener {
}
if (mListener != null) {
mListener.onTitleTextChange(R.string.courses);
mListener.getKVV(kvv -> {
kvv.modules().list().recv(success -> {
Modules.Module module = success.get(mItemPos);
if (mListener != null && module != null)
mListener.onTitleTextChange(module.title);
}, log::e);
});
mListener.getKVV().modules().list().recv(success -> {
Modules.Module module = success.get(mItemPos);
if (mListener != null && module != null)
mListener.onTitleTextChange(module.title);
}, log::e);
}
}

View File

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

View File

@@ -2,7 +2,6 @@ package de.sebse.fuplanner.fragments.moddetails;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
@@ -22,6 +21,7 @@ import de.sebse.fuplanner.services.kvv.types.Event;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
import de.sebse.fuplanner.tools.ui.MailViewHolder;
@@ -37,12 +37,12 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private static final int TYPE_SHOW_MORE = 3;
private static final int TYPE_MAIL = 4;
private static final int TYPE_SHORTCUTS = 5;
private static final int TYPE_NO_ITEMS = 6;
@Nullable private final ModDetailListener mListener;
private Modules.Module mValue;
private final ArrayList<Pair<Integer, Object>> mPositionalData;
private Logger log = new Logger(this);
ModDetailOverviewAdapter(@Nullable final ModDetailListener listener) {
mValue = null;
@@ -57,10 +57,8 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private void setModule() {
mPositionalData.clear();
if (!TextUtils.isEmpty(mValue.description)) {
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.DESCRIPTION));
mPositionalData.add(new Pair<>(TYPE_DESCRIPTION, null));
}
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.DESCRIPTION));
mPositionalData.add(new Pair<>(TYPE_DESCRIPTION, null));
mPositionalData.add(new Pair<>(TYPE_SHORTCUTS, null));
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.LECTURERS));
for (int i = 0; i < mValue.lecturer.size(); i++) {
@@ -81,9 +79,6 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
}
if (count > MAX_ITEMS_PER_PREVIEW)
mPositionalData.add(new Pair<>(TYPE_SHOW_MORE, category));
if (count == 0) {
mPositionalData.add(new Pair<>(TYPE_NO_ITEMS, category));
}
}
@NonNull
@@ -107,10 +102,6 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_all_show_more, parent, false);
return new CustomViewHolder(view);
case TYPE_NO_ITEMS:
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_all_no_items, parent, false);
return new CustomViewHolder(view);
case TYPE_MAIL:
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_all_mails, parent, false);
@@ -202,9 +193,9 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
else
start = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getStartDate());
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
end = UtilsDate.getModifiedTime(i.mView.getContext(), event.getEndDate()+1);
end = UtilsDate.getModifiedTime(i.mView.getContext(), event.getEndDate());
else
end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate()+1);
end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate());
i.mSubRight.setText(i.mView.getResources().getString(R.string.date_scale,
start, end
));
@@ -245,7 +236,6 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
});
break;
case TYPE_SHOW_MORE:
case TYPE_NO_ITEMS:
CustomViewHolder c = (CustomViewHolder) holder;
c.mView.setOnClickListener(view -> {
if (mListener != null) mListener.gotoFragmentPart((Integer) data.second, -1);

View File

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

View File

@@ -24,7 +24,6 @@ import de.sebse.fuplanner.services.kvv.types.Resource;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.treeview.DirectoryNodeBinder;
import de.sebse.fuplanner.tools.ui.treeview.DocumentNodeBinder;
import de.sebse.fuplanner.tools.ui.treeview.FileNodeBinder;
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
import de.sebse.fuplanner.tools.ui.treeview.TreeViewAdapter;
@@ -34,7 +33,7 @@ import de.sebse.fuplanner.tools.ui.treeview.TreeViewAdapter;
* Use the {@link ModDetailResourceFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ModDetailResourceFragment extends Fragment implements Download.OnDownloadRequestInterface {
public class ModDetailResourceFragment extends Fragment {
private static final String ARG_POSITION = "itemPosition";
private String mItemPos;
@@ -82,7 +81,7 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
RecyclerView recyclerView = view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder(), new DocumentNodeBinder(this)));
adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder()));
adapter.setOnTreeNodeListener(new TreeViewAdapter.OnTreeNodeListener() {
@Override
public boolean onClick(TreeNode node, RecyclerView.ViewHolder holder) {
@@ -90,13 +89,11 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
// Update and toggle the node.
onToggle(!node.isExpand(), holder);
} else if (node.getContent() instanceof Resource.File && ModDetailResourceFragment.this.mListener != null) { // if leaf is file
ModDetailResourceFragment.this.mListener.getKVV(kvv -> {
kvv.modules().resources().recv(mItemPos, (Modules.Module module) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
Resource.File file = (Resource.File) node.getContent();
getDownload().openDownloadDialog(file, folderName);
}, log::e);
});
ModDetailResourceFragment.this.mListener.getKVV().modules().resources().recv(mItemPos, (Modules.Module module) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
Resource.File file = (Resource.File) node.getContent();
getDownload().openDownloadDialog(file, folderName);
}, log::e);
}
return false;
}
@@ -121,19 +118,6 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
return view;
}
@Override
public void request(String title, String url) {
if (mListener == null)
return;
mListener.getKVV(kvv -> {
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Announcement";
getDownload().openDownloadDialog(title, url, folderName);
}, log::e);
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
@@ -154,18 +138,16 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
}
private void refresh(boolean forceRefresh) {
if (mListener != null) {
mListener.getKVV(kvv -> {
kvv.modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
});
}
if (mListener == null)
return;
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
adapter.setModule(pair.first);
if (pair.second)
swipeLayout.setRefreshing(false);
}, error -> {
swipeLayout.setRefreshing(false);
log.e(error);
}, forceRefresh);
}
private Download getDownload() {

View File

@@ -1,13 +1,13 @@
package de.sebse.fuplanner.fragments.moddetails;
public class ModulePart {
class ModulePart {
static final int DESCRIPTION = 0;
static final int OVERVIEW = 1;
public static final int ANNOUNCEMENT = 2;
public static final int ASSIGNMENT = 3;
public static final int EVENT = 4;
public static final int GRADEBOOK = 5;
public static final int RESOURCES = 6;
static final int ANNOUNCEMENT = 2;
static final int ASSIGNMENT = 3;
static final int EVENT = 4;
static final int GRADEBOOK = 5;
static final int RESOURCES = 6;
static final int LECTURERS = 7;
private static final int[] pages = new int[]{OVERVIEW, ANNOUNCEMENT, ASSIGNMENT, GRADEBOOK, RESOURCES, EVENT};

View File

@@ -1,7 +1,6 @@
package de.sebse.fuplanner.services.canteen;
import android.content.Context;
import android.os.Build;
import org.json.JSONArray;
import org.json.JSONException;
@@ -65,11 +64,6 @@ public class CanteenBrowser extends HTTPService {
}
private void upgradeCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(new Canteens());
return;
}
get("https://openmensa.org/api/v2/canteens?near[lat]=52.449743&near[lng]=13.282245&near[dist]=7", null, response -> {
String body = response.getParsed();
if (body == null) {
@@ -131,11 +125,6 @@ public class CanteenBrowser extends HTTPService {
}
private void upgradeCanteen(Canteen canteen, final NetworkCallback<Canteen> callback, final NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(canteen);
return;
}
get(String.format("https://openmensa.org/api/v2/canteens/%s/days", canteen.getId()), null, response -> {
String body = response.getParsed();
if (body == null) {
@@ -183,11 +172,6 @@ public class CanteenBrowser extends HTTPService {
}
private void upgradeDay(Day day, final NetworkCallback<Day> callback, final NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(day);
return;
}
get(String.format("https://openmensa.org/api/v2/canteens/%s/days/%s/meals/", day.getCanteenId(), Canteen.calendarToKey(day.getCalendar())), null, response -> {
String body = response.getParsed();
if (body == null) {

View File

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

View File

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

View File

@@ -14,13 +14,9 @@ import java.util.concurrent.atomic.AtomicReference;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.sync.BBLogin;
import de.sebse.fuplanner.services.kvv.sync.FULogin;
import de.sebse.fuplanner.services.kvv.sync.KVVLogin;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.services.kvv.sync.Login;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
/**
@@ -38,23 +34,20 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
};*/
static final String PARAM_USER_PASS = "PARAM_USER_PASS";
private final String mUsername;
private final String mEmail;
private final String mPassword;
private final KVVLogin mKVVLogin;
private final BBLogin mBBLogin;
private final Login mVolleyLogin;
private String mTokenType;
private Logger log = new Logger(this);
@SuppressLint("StaticFieldLeak")
@Nullable
private FUAuthenticatorActivity mActivity;
UserLoginTask(String username, String password, @NotNull String tokenType, @NotNull Context context) {
mUsername = username;
UserLoginTask(String email, String password, String tokenType, @NotNull Context context) {
mEmail = email;
mPassword = password;
mTokenType = tokenType;
FULogin mFULogin = new FULogin(context);
mKVVLogin = new KVVLogin(context, mFULogin);
mBBLogin = new BBLogin(context, mFULogin);
mVolleyLogin = new Login(context);
if (context instanceof FUAuthenticatorActivity)
mActivity = (FUAuthenticatorActivity) context;
}
@@ -64,59 +57,37 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
// TODO: attempt authentication against a network service.
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> login = new AtomicReference<>();
NetworkErrorCallback errorFunc = error -> {
log.e(error);
login.set("Error: "+String.valueOf(error.getCode()));
latch.countDown();
};
switch (mTokenType) {
case AccountGeneral.AUTHTOKEN_TYPE_KVV:
mKVVLogin.doLogin(mUsername, mPassword, success -> {
mKVVLogin.testLoginToken(success, success1 -> {
login.set(success1.toJsonString());
latch.countDown();
}, errorFunc);
}, error -> {
if (error.getCode() == 100101) {
// KVV never used
LoginTokenKVV loginTokenKVV = new LoginTokenKVV(mUsername, "");
loginTokenKVV.setNotAvailable();
login.set(loginTokenKVV.toJsonString());
latch.countDown();
} else {
errorFunc.onError(error);
}
});
break;
case AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD:
mBBLogin.doLogin(mUsername, mPassword, success -> {
mBBLogin.testLoginToken(success, success1 -> {
login.set(success1.toJsonString());
latch.countDown();
}, error -> {
if (error.getCode() == 100270) {
// Blackboard never used
success.setNotAvailable();
login.set(success.toJsonString());
latch.countDown();
} else {
errorFunc.onError(error);
}
});
}, errorFunc);
break;
default:
errorFunc.onError(new NetworkError(104100, 400, "Invalid auth token type"));
return null;
}
AtomicReference<LoginToken> login = new AtomicReference<>();
mVolleyLogin.doLogin(mEmail, mPassword, success -> {
mVolleyLogin.testLoginToken(success, success1 -> {
login.set(success);
latch.countDown();
}, error -> latch.countDown());
}, error -> latch.countDown());
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return login.get();
log.d(login.get());
if (login.get() == null) {
return null;
} else {
return login.get().toJsonString();
}
/*for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword) ? "auth token here" : null;
}
}
// TODO: register the new account here.
return null;*/
}
@Override
@@ -128,20 +99,16 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
mActivity.mAuthTask = null;
mActivity.showProgress(false);
if (success != null && !success.startsWith("Error: ")) {
if (success != null) {
final Intent res = new Intent();
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mEmail);
res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountGeneral.ACCOUNT_TYPE);
res.putExtra(AccountManager.KEY_AUTHTOKEN, success);
res.putExtra(PARAM_USER_PASS, mPassword);
mActivity.finishLogin(res);
} else if (success != null && (success.contains("100343"))) {
} else {
mActivity.mPasswordView.setError(mActivity.getString(R.string.error_incorrect_password));
mActivity.mPasswordView.requestFocus();
} else if (success != null) {
mActivity.mErrorView.setText(mActivity.getString(R.string.network_error_parameter, success.substring(7)));
} else {
mActivity.mErrorView.setText(R.string.network_error);
}
}

View File

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

View File

@@ -1,104 +1,31 @@
package de.sebse.fuplanner.services.kvv;
import android.accounts.AccountManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.android.volley.NetworkResponse;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.tools.CustomAccountManager;
public class KVV extends Service {
public class KVV {
private final HashMap<String, Object> addons = new HashMap<>();
private final HashMap<String, KVVListener> mListeners = new HashMap<>();
private final KVVListener mListener = new KVVListener() {
CustomAccountManager accountManager = null;
private final KVVListener mListener;
private final Context mContext;
@Override
public CustomAccountManager getAccountManager() {
if (accountManager == null)
accountManager = new CustomAccountManager(AccountManager.get(KVV.this.getApplicationContext()), () -> null);
return accountManager;
}
@Override
public void onKVVNetworkResponse(NetworkResponse error) {
for (KVVListener listener : mListeners.values())
listener.onKVVNetworkResponse(error);
}
@Override
public void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {
for (KVVListener listener : mListeners.values())
listener.onLogin(tokenKVV, tokenBB, isOnlyRefresh);
}
@Override
public void onLogout() {
for (KVVListener listener : mListeners.values())
listener.onLogout();
}
@Override
public void onModuleListChange() {
for (KVVListener listener : mListeners.values())
listener.onModuleListChange();
}
@Override
public void onModuleListPartiallyUpdated(de.sebse.fuplanner.services.kvv.types.Modules modules) {
for (KVVListener listener : mListeners.values())
listener.onModuleListPartiallyUpdated(modules);
}
};
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
public KVV(KVVListener listener, Context context) {
this.mListener = listener;
this.mContext = context;
}
@NotNull
public Login account() {
return (Login) addAndGet("account", () -> new Login(mListener, getApplicationContext()));
return (Login) addAndGet("account", () -> new Login(mListener, mContext));
}
@NotNull
public Modules modules() {
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, getApplicationContext()));
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, mContext));
}
public void addListener(String key, KVVListener listener) {
mListeners.put(key, listener);
}
public void removeListener(String key) {
mListeners.remove(key);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public KVV getService() {
// Return this instance of LocalService so clients can call public methods
return KVV.this;
}
}

View File

@@ -2,20 +2,16 @@ package de.sebse.fuplanner.services.kvv;
import com.android.volley.NetworkResponse;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.tools.CustomAccountManager;
public interface KVVListener {
default void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {}
default void onLogin(LoginToken token) {}
default void onLogout() {}
default void onModuleListChange() {}
default void onModuleListPartiallyUpdated(Modules modules) {}
default void onKVVNetworkResponse(NetworkResponse error) {}
CustomAccountManager getAccountManager();

View File

@@ -1,89 +1,59 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import android.util.Pair;
import org.jetbrains.annotations.NotNull;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.sync.BBLogin;
import de.sebse.fuplanner.services.kvv.sync.FULogin;
import de.sebse.fuplanner.services.kvv.sync.KVVLogin;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.NetworkCallbackCollector;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class Login extends HTTPService {
public static final int RESTORE_STATUS_SUCCESS = 1;
public static final int RESTORE_STATUS_ERROR = 2;
public static final int RESTORE_STATUS_INVALID_PASSWORD = 3;
public static final int LOGOUT_KVV = 2;
public static final int LOGOUT_BB = 1;
public static final int RELOGIN = 0;
private final KVVListener mListener;
@Nullable private LoginTokenKVV mTokenKVV;
@Nullable private LoginTokenBB mTokenBB;
@Nullable private LoginToken mToken;
private boolean mLoginPending = false;
private final NetworkCallbackCollector<Pair<LoginTokenKVV, LoginTokenBB>> mRefreshCallbacks = new NetworkCallbackCollector<>();
private final NetworkCallbackCollector<Integer> mRestoreCallbacks = new NetworkCallbackCollector<>();
private final NetworkCallbackCollector<LoginToken> mRefreshCallbacks = new NetworkCallbackCollector<>();
Login(KVVListener listener, Context context) {
super(context);
this.mListener = listener;
}
public void restoreOnlineLogin(IntegerInterface callback) {
mRestoreCallbacks.add(new Pair<>(callback::run, null));
public void restoreOnlineLogin(BooleanInterface callback) {
if (mLoginPending) {
callback.run(false);
return;
}
mLoginPending = true;
LoginTokenKVV.load(mListener.getAccountManager(), tokenKVV -> {
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
boolean result = setToken(tokenKVV, tokenBB);
mLoginPending = false;
mRestoreCallbacks.responseResponse(result ? RESTORE_STATUS_SUCCESS : RESTORE_STATUS_INVALID_PASSWORD);
}, e -> {
mLoginPending = false;
mRestoreCallbacks.responseResponse(RESTORE_STATUS_ERROR);
});
}, e -> {
LoginToken.load(mListener.getAccountManager(), token -> {
boolean result = setToken(token);
mLoginPending = false;
mRestoreCallbacks.responseResponse(RESTORE_STATUS_ERROR);
log.d("loginToken", token != null ? token.toString() : null);
callback.run(result);
});
}
public void isOfflineStoredAvailable(BooleanInterface callback) {
LoginTokenKVV.load(mListener.getAccountManager(), tokenKVV -> {
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
callback.run(tokenKVV != null && tokenBB != null);
}, e -> callback.run(false));
}, e -> callback.run(false));
LoginToken.load(mListener.getAccountManager(), token -> {
callback.run(token != null);
});
}
public boolean logout(boolean delete) {
if (mLoginPending)
return false;
if (mTokenKVV == null || mTokenBB == null)
if (mToken == null)
return true;
if (delete) {
Preferences.setString(getContext(), R.string.pref_shib_idp_session, "");
mTokenKVV.delete(mListener.getAccountManager());
mTokenBB.delete(mListener.getAccountManager());
}
mTokenKVV = null;
mTokenBB = null;
return handleCallbacks(false);
if (delete)
mToken.delete(mListener.getAccountManager());
mToken = null;
return handleCallbacks();
}
public boolean isLoginPending() {
@@ -91,81 +61,52 @@ public class Login extends HTTPService {
}
public boolean isLoggedIn() {
return mTokenKVV != null && mTokenBB != null;
return mToken != null;
}
public boolean isInOnlineMode() {
return isLoggedIn();
}
void testLoginToken(@NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
if (mTokenKVV == null) {
void testLoginToken(@NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
if (mToken == null) {
errorCallback.onError(new NetworkError(100173, -1, "Not logged in!"));
return;
}
if (mTokenBB == null) {
errorCallback.onError(new NetworkError(100174, -1, "Not logged in!"));
return;
}
testLoginToken(mTokenKVV, mTokenBB, callback, errorCallback);
testLoginToken(mToken, callback, errorCallback);
}
private void testLoginToken(@NotNull LoginTokenKVV tokenKVV, @NotNull LoginTokenBB tokenBB, @NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
FULogin mFULogin = new FULogin(getContext());
new KVVLogin(getContext(), mFULogin).testLoginToken(tokenKVV, tokenKVV1 -> {
new BBLogin(getContext(), mFULogin).testLoginToken(tokenBB, tokenBB1 -> {
callback.onResponse(new Pair<>(tokenKVV1, tokenBB1));
}, errorCallback);
}, errorCallback);
private void testLoginToken(@NotNull LoginToken token, @NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
new de.sebse.fuplanner.services.kvv.sync.Login(getContext()).testLoginToken(token, callback, errorCallback);
}
@Nullable public LoginTokenKVV getLoginTokenKVV() {
return mTokenKVV;
@Nullable public LoginToken getLoginToken() {
return mToken;
}
@Nullable public LoginTokenBB getLoginTokenBB() {
return mTokenBB;
}
void refreshLogin(NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
void refreshLogin(NetworkCallback<LoginToken> success, NetworkErrorCallback error) {
boolean isFirst = mRefreshCallbacks.isEmpty();
mRefreshCallbacks.add(success, error);
if (!isFirst)
return;
refreshLoginRunner(success, error, flags);
}
private void refreshLoginRunner(NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
CustomAccountManager manager = mListener.getAccountManager();
if ((flags & LOGOUT_KVV) == LOGOUT_KVV) {
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, ignored -> {
refreshLoginRunner(success, error, flags & ~LOGOUT_KVV);
});
} else if ((flags & LOGOUT_BB) == LOGOUT_BB) {
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, ignored -> {
refreshLoginRunner(success, error, flags & ~LOGOUT_BB);
});
} else if (flags == RELOGIN) {
restoreOnlineLogin(restoreResult -> {
if (restoreResult == RESTORE_STATUS_SUCCESS)
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, ignored -> {
restoreOnlineLogin(isRestored -> {
if (isRestored)
testLoginToken(mRefreshCallbacks::responseResponse, mRefreshCallbacks::responseError);
else if (restoreResult == RESTORE_STATUS_INVALID_PASSWORD) {
else {
logout(true);
mRefreshCallbacks.responseError(new NetworkError(100180, 403, "Re-login failed (password)!"));
} else {
mRefreshCallbacks.responseError(new NetworkError(100181, 403, "Re-login failed (error)!"));
mRefreshCallbacks.responseError(new NetworkError(100180, 403, "Re-login failed!"));
}
});
} else {
throw new IllegalArgumentException("Invalid flag in refreshLoginRunner: "+flags);
}
});
}
private boolean handleCallbacks(boolean isOnlyRefresh) {
if (mTokenKVV != null || mTokenBB != null) {
mListener.onLogin(mTokenKVV, mTokenBB, isOnlyRefresh);
private boolean handleCallbacks() {
if (mToken != null) {
mListener.onLogin(mToken);
return true;
} else {
mListener.onLogout();
@@ -173,20 +114,15 @@ public class Login extends HTTPService {
}
}
private boolean setToken(@Nullable LoginTokenKVV tokenKVV, @Nullable LoginTokenBB tokenBB) {
if (tokenKVV == null || tokenBB == null)
private boolean setToken(@Nullable LoginToken token) {
if (token == null)
return false;
boolean isOnlyRefresh = mTokenKVV != null;
mTokenKVV = tokenKVV;
mTokenBB = tokenBB;
return isOnlyRefresh || handleCallbacks(isOnlyRefresh);
boolean isOnlyRefresh = mToken != null;
mToken = token;
return isOnlyRefresh || handleCallbacks();
}
public interface BooleanInterface {
void run(boolean bool);
}
public interface IntegerInterface {
void run(int integer);
}
}

View File

@@ -2,8 +2,6 @@ package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import com.android.volley.NetworkResponse;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
@@ -58,13 +56,7 @@ public class Modules {
public ModulesList list() {
if (mList == null) {
mList = new ModulesList(mLogin, mListener, context);
mList.addErrorListener("Modules", error -> {
NetworkResponse networkResponse = error.networkResponse;
if ((networkResponse.statusCode == 400 || networkResponse.statusCode == 403) && networkResponse.headers.containsKey("X-Blackboard-product"))
mListener.onKVVNetworkResponse(null);
else
mListener.onKVVNetworkResponse(networkResponse);
});
mList.addErrorListener("Modules", error -> mListener.onKVVNetworkResponse(error.networkResponse));
mList.addSuccessListener("Modules", success -> mListener.onKVVNetworkResponse(null));
}
return mList;
@@ -76,13 +68,7 @@ public class Modules {
Part o = mAddons.get(addon);
if (o == null) {
o = creatorInterface.create();
o.addErrorListener("Modules", error -> {
NetworkResponse networkResponse = error.networkResponse;
if ((networkResponse.statusCode == 400 || networkResponse.statusCode == 403) && networkResponse.headers.containsKey("X-Blackboard-product"))
mListener.onKVVNetworkResponse(null);
else
mListener.onKVVNetworkResponse(networkResponse);
});
o.addErrorListener("Modules", error -> mListener.onKVVNetworkResponse(error.networkResponse));
o.addSuccessListener("Modules", success -> mListener.onKVVNetworkResponse(null));
mAddons.put(addon, o);
}

View File

@@ -10,7 +10,6 @@ import java.util.ArrayList;
import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
@@ -34,12 +33,12 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
}
@Override
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101204, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format(Constants.KVV_SERVER_URL+"direct/announcement/site/%s.json?n=999999&d=999999999&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
super.get(String.format("https://kvv.imp.fu-berlin.de/direct/announcement/site/%s.json?n=999999&d=999999999", ID), mLogin.getLoginToken().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101201, 403, "No announcements retrieved!"));
@@ -82,59 +81,11 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
}
}
callback.onResponse(announcements);
// Empty announcements *may be* because token is invalid -> check
if (announcements.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(announcements), errorCallback);
else
callback.onResponse(announcements);
}, error -> errorCallback.onError(new NetworkError(101203, error.networkResponse.statusCode, "Cannot get announcements!")));
}
@Override
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Announcement>> callback, NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101214, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format("https://lms.fu-berlin.de/learn/api/v1/courses/%s/announcements?fields=id,title,body.rawText,startDateRestriction,creatorUserId", ID), mLogin.getLoginTokenBB().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101211, 403, "No announcements retrieved!"));
return;
}
ArrayList<Announcement> announcements = new ArrayList<>();
JSONArray sites;
try {
JSONObject json = new JSONObject(body);
sites = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101212, 403, "Cannot parse announcements!"));
return;
}
for (int i = 0; i < sites.length(); i++) {
try {
JSONObject site = sites.getJSONObject(i);
String id = site.getString("id");
String title = site.getString("title");
String text = site.getJSONObject("body").getString("rawText");
text = String.valueOf(fromHtml(text));
String createdBy = "";//site.getStringArray("createdByDisplayName");
long createdOn = UtilsDate.stringToMillis(site.getString("startDateRestriction"), "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
ArrayList<String> urls = new ArrayList<>();
announcements.add(new Announcement(id, title, text, createdBy, createdOn, urls));
} catch (JSONException e) {
log.e(new NetworkError(101215, 403, "Cannot parse announcements!"));
log.e("ID:", i, "JSON:", sites);
e.printStackTrace();
return;
}
}
callback.onResponse(announcements);
}, error -> {
if (error.networkResponse.statusCode == 400)
callback.onResponse(new ArrayList<>());
else
errorCallback.onError(new NetworkError(101213, error.networkResponse.statusCode, "Cannot get announcements!"));
});
}
}

View File

@@ -34,12 +34,12 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
}
@Override
protected void upgradeKVV(final String ID, final NetworkCallback<AssignmentList> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
protected void upgrade(final String ID, final NetworkCallback<AssignmentList> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101304, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/assignment/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format("https://kvv.imp.fu-berlin.de/direct/assignment/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101301, 403, "No assignments retrieved!"));
@@ -80,12 +80,11 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
}
}
callback.onResponse(assignments);
// Empty assignments *may be* because token is invalid -> check
if (assignments.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(assignments), errorCallback);
else
callback.onResponse(assignments);
}, error -> errorCallback.onError(new NetworkError(101303, error.networkResponse.statusCode, "Cannot get assignments!")));
}
@Override
protected void upgradeBB(String ID, NetworkCallback<AssignmentList> callback, NetworkErrorCallback errorCallback) {
callback.onResponse(new AssignmentList());
}
}

View File

@@ -1,30 +1,20 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.regex.MatchResult;
import de.sebse.fuplanner.services.kvv.types.Event;
import de.sebse.fuplanner.services.kvv.types.EventList;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.kvv.types.Semester;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class ModulesEvents extends PartModules<EventList> {
private ModulesEventsNumber mEventNumbers;
ModulesEvents(Login login, ModulesList list, Context context) {
super(login, list, context);
}
@@ -42,12 +32,12 @@ public class ModulesEvents extends PartModules<EventList> {
}
@Override
protected void upgradeKVV(final String ID, final NetworkCallback<EventList> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
protected void upgrade(final String ID, final NetworkCallback<EventList> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101404, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format("https://kvv.imp.fu-berlin.de/direct/calendar/site/%s.json?detailed=true", ID), mLogin.getLoginToken().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101401, 403, "No events retrieved!"));
@@ -83,106 +73,11 @@ public class ModulesEvents extends PartModules<EventList> {
}
}
callback.onResponse(events);
// Empty events *may be* because token is invalid -> check
if (events.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(events), errorCallback);
else
callback.onResponse(events);
}, error -> errorCallback.onError(new NetworkError(101403, error.networkResponse.statusCode, "Cannot get events!")));
}
@Override
protected void upgradeBB(String ID, NetworkCallback<EventList> callback, NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(new EventList());
return;
}
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101414, 500, "Currently running in offline mode!"));
return;
}
this.mList.recv(modules -> {
Modules.Module module = modules.get(ID);
if (module == null) {
errorCallback.onError(new NetworkError(101416, 400, "Cannot get events!"));
return;
}
Semester latestSemester = modules.getLatestSemester();
if (module.semester != null && !module.semester.equals(latestSemester)) {
if (module.events != null) {
callback.onResponse(module.events);
} else {
callback.onResponse(new EventList());
}
return;
}
if (module.lvNumber.size() == 0) {
// Events not available
callback.onResponse(new EventList());
return;
}
eventNumbers().getVVNumber(module.lvNumber.iterator().next(), vvNumber -> {
if (vvNumber.equals("")) {
// Events not available
callback.onResponse(new EventList());
//errorCallback.onError(new NetworkError(101410, 403, "Cannot get events!"));
return;
}
// 462854, 465661, 462126, 463782, 437050, 433843, 471614, 464205
//String[] tests = {"462854", "465661", "462126", "463782", "437050", "433843", "471614", "464205"};
//String[] tests = {"461459", "424564", "459494", "429737", "463765", "476477", "464082", "459577", "459743", "464318", "449358", "454327", "461784", "468081", "485919"};
//vvNumber = tests[new Random().nextInt(tests.length)];
//log.d("LAAAAAAST", vvNumber);
//vvNumber = "462126";
super.get(String.format("https://www.fu-berlin.de/vv/de/lv/%s", vvNumber), null, response1 -> {
String body = response1.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101411, 400, "Cannot get events!"));
return;
}
EventList events = new EventList();
for (MatchResult match : Regex.allMatches("<span id=\"link_to_details_[^~]*?</span>", body)) {
String entry = match.group(0);
String date;
String title = "";
try {
date = Regex.regex("[A-Z][a-z], [0-9]{2}\\.[0-9]{2}\\.[0-9]{4} [0-9]{2}:[0-9]{2} - [0-9]{2}:[0-9]{2}", entry, 0);
} catch (NoSuchFieldException e) {
log.e(new NetworkError(101412, 400, "Cannot get events!"));
e.printStackTrace();
continue;
}
try {
title = Regex.regex("<div class=\"course_title\">([^<]*?)</div>", entry, 1);
} catch (NoSuchFieldException ignored) {}
if (TextUtils.isEmpty(title))
title = module.title;
ArrayList<String> docents = new ArrayList<>();
ArrayList<String> locations = new ArrayList<>();
for (MatchResult match1 : Regex.allMatches("<div class=\"appointment_details_column\">[^~]*?</div>", entry)) {
if (match1.group(0).contains("Dozenten:")) {
for (MatchResult match2 : Regex.allMatches(">([^>]*?)<small class=\"phone_portal\">", match1.group(0))) {
docents.add(match2.group(0).trim());
}
} else if (match1.group(0).contains("Räume:")) {
for (MatchResult match2 : Regex.allMatches("</b>([^~]*?)</p>", match1.group(0))) {
locations.add(match2.group(1).trim());
}
}
}
long start = UtilsDate.stringToMillis(date.substring(4, 20), "dd.MM.yyyy HH:mm");
long duration = (Integer.parseInt(date.substring(23, 25))-Integer.parseInt(date.substring(15, 17)))*60
+ Integer.parseInt(date.substring(26, 28))-Integer.parseInt(date.substring(18, 20));
duration = duration*60*1000-1;
String locationString = TextUtils.join(", ", locations);
events.add(new Event("", "Class section - Lecture", title, duration, start, ID, locationString));
}
callback.onResponse(events);
}, error -> errorCallback.onError(new NetworkError(101415, error.networkResponse.statusCode, "Cannot get events!")));
}, errorCallback);
}, errorCallback);
}
private ModulesEventsNumber eventNumbers() {
if (mEventNumbers == null)
mEventNumbers = new ModulesEventsNumber(getContext());
return mEventNumbers;
}
}

View File

@@ -1,72 +0,0 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import de.sebse.fuplanner.services.kvv.types.CacheBBEventNumber;
import de.sebse.fuplanner.services.kvv.types.CacheLecturer;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
class ModulesEventsNumber extends HTTPService {
private final CacheBBEventNumber mStorage;
ModulesEventsNumber(Context context) {
super(context);
CacheBBEventNumber storage = null;
try {
storage = CacheBBEventNumber.load(context);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (storage == null) {
mStorage = new CacheBBEventNumber();
} else {
mStorage = storage;
}
}
void getVVNumber(String lvNumber, NetworkCallback<String> callback, NetworkErrorCallback errorCallback) {
String vvNumber = mStorage.getVVNumber(lvNumber);
if (vvNumber != null) {
callback.onResponse(vvNumber);
return;
}
super.head(String.format("https://www.fu-berlin.de/vv/de/search?utf8=✓&query=%s", lvNumber), null, response -> {
String location = response.getHeaders().get("Location");
if (location == null) {
// Events not available
callback.onResponse("");
//errorCallback.onError(new NetworkError(101410, 403, "Cannot get events!"));
return;
}
try {
String group = Regex.regex("lv/([0-9]+)\\?", location);
mStorage.setVVNumber(lvNumber, group);
try {
mStorage.save(getContext());
} catch (IOException e) {
e.printStackTrace();
}
callback.onResponse(group);
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(102201, 400, "Cannot get events!"));
e.printStackTrace();
}
}, error -> errorCallback.onError(new NetworkError(102202, error.networkResponse.statusCode, "Error retrieving lecturer!")));
}
}

View File

@@ -33,12 +33,12 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
}
@Override
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Grade>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Grade>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101504, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format(Constants.KVV_SERVER_URL+"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
super.get(String.format("https://kvv.imp.fu-berlin.de/direct/gradebook/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101501, 403, "No gradebook retrieved!"));
@@ -71,85 +71,6 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
}
}
callback.onResponse(gradebook);
}, error -> {
if (error.networkResponse.statusCode == 400)
callback.onResponse(new ArrayList<>());
else
errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!"));
});
}
@Override
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Grade>> callback, NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101510, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format("https://lms.fu-berlin.de/learn/api/public/v2/courses/%s/gradebook/columns", ID), mLogin.getLoginTokenBB().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101511, 400, "No gradebook columns retrieved!"));
return;
}
JSONArray gradeColumns;
try {
JSONObject json = new JSONObject(body);
gradeColumns = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101512, 400, "Cannot parse gradebook columns!"));
return;
}
get(String.format("https://lms.fu-berlin.de/learn/api/public/v2/courses/%s/gradebook/users/%s", ID, mLogin.getLoginTokenBB().getId()), mLogin.getLoginTokenBB().getCookies(), response1 -> {
String body1 = response1.getParsed();
if (body1 == null) {
errorCallback.onError(new NetworkError(101513, 400, "No gradebook entries retrieved!"));
return;
}
JSONArray grades;
try {
JSONObject json = new JSONObject(body1);
grades = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101514, 400, "Cannot parse gradebook entries!"));
return;
}
ArrayList<Grade> result = new ArrayList<>();
for (int i = 0; i < grades.length(); i++) {
for (int j = 0; j < gradeColumns.length(); j++) {
try {
JSONObject grade = grades.getJSONObject(i);
JSONObject column = gradeColumns.getJSONObject(j);
String grade_id = grade.getString("columnId");
String column_id = column.getString("id");
if (!grade_id.equals(column_id))
continue;
String name = column.getString("name");
JSONObject displayGrade = grade.optJSONObject("displayGrade");
double points = displayGrade != null ? displayGrade.optDouble("score", 0) : 0;
JSONObject score = column.optJSONObject("score");
double maxPoints = score != null ? score.optDouble("possible", 0) : 0;
result.add(new Grade(name, points, maxPoints));
} catch (JSONException e) {
log.e(new NetworkError(101515, 400, "Cannot parse grades!"));
log.e("ID:", i, "JSON-grades:", grades);
log.e("ID:", j, "JSON-gradeColumns:", gradeColumns);
e.printStackTrace();
return;
}
}
}
callback.onResponse(result);
}, error -> errorCallback.onError(new NetworkError(101516, error.networkResponse.statusCode, "Cannot get gradebook columns!")));
}, error -> {
if (error.networkResponse.statusCode == 403)
callback.onResponse(new ArrayList<>());
else
errorCallback.onError(new NetworkError(101517, error.networkResponse.statusCode, "Cannot get gradebook entries!"));
});
}, error -> errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!")));
}
}

View File

@@ -12,11 +12,7 @@ import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import androidx.arch.core.util.Function;
import de.sebse.fuplanner.services.kvv.types.CacheBBCourse;
import de.sebse.fuplanner.services.kvv.types.CacheKVVCourse;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.kvv.types.Semester;
@@ -33,10 +29,7 @@ public class ModulesList extends HTTPService {
private final Login mLogin;
private final KVVListener mListener;
@Nullable private Modules mModules;
private ModulesListLecturer mLecturer;
private CacheBBCourse mBBCache;
private final NewAsyncQueue mQueue = new NewAsyncQueue();
private CacheKVVCourse mKVVCache;
ModulesList(Login login, KVVListener listener, Context context) {
super(context);
@@ -53,28 +46,14 @@ public class ModulesList extends HTTPService {
return null;
}
public void reloadIfOutdated() {
try {
if (mModules != null && mModules.isNewerVersionInStorage(getContext())) {
restore();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void find(String moduleID, NetworkCallback<Modules.Module> moduleNetworkCallback, NetworkErrorCallback errorCallback) {
find(moduleID, moduleNetworkCallback, errorCallback, RETRY_COUNT);
}
private void find(String moduleID, NetworkCallback<Modules.Module> moduleNetworkCallback, NetworkErrorCallback errorCallback, int retries) {
if (mModules != null &&
mLogin.getLoginTokenKVV() != null && mLogin.getLoginTokenKVV().isOtherUser(mModules.getUsername()) &&
mLogin.getLoginTokenBB() != null && mLogin.getLoginTokenBB().isOtherUser(mModules.getUsername())
)
if (mModules != null && mLogin.getLoginToken() != null && mLogin.getLoginToken().isOtherUser(mModules.getUsername()))
delete();
if (retries < 0) {
log.t("Too many retires", retries);
errorCallback.onError(new NetworkError(101107, -1, "Too many retries!"));
return;
}
@@ -107,9 +86,6 @@ public class ModulesList extends HTTPService {
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (this.mModules == null) {
recv(success -> {}, log::e);
}
}
public void delete() {
@@ -128,330 +104,101 @@ public class ModulesList extends HTTPService {
}
private void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh, final int retries) {
if (mModules != null &&
mLogin.getLoginTokenKVV() != null && mLogin.getLoginTokenKVV().isOtherUser(mModules.getUsername()) &&
mLogin.getLoginTokenBB() != null && mLogin.getLoginTokenBB().isOtherUser(mModules.getUsername())
)
if (mModules != null && mLogin.getLoginToken() != null && mLogin.getLoginToken().isOtherUser(mModules.getUsername()))
delete();
mQueue.add(() -> {
if (mLogin.isLoginPending()) {
mLogin.restoreOnlineLogin(resCode -> {
mQueue.next();
});
} else {
mQueue.next();
}
});
mQueue.add(() -> {
if (this.mModules != null && !forceRefresh) {
callback.onResponse(this.mModules);
mQueue.next();
return;
}
Function<Integer, NetworkErrorCallback> errorFunc = ((Integer errorCode) -> (error -> {
this.upgrade(success -> {
if (this.mModules == null)
this.mModules = success;
else if (this.mModules.updateList(success)) {
mListener.onModuleListChange();
store();
}
callback.onResponse(this.mModules);
mQueue.next();
}, error -> {
if (retries > 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
mLogin.refreshLogin(success -> {
recv(callback, errorCallback, forceRefresh, retries - 1);
recv(callback, errorCallback, forceRefresh, retries-1);
mQueue.next();
}, error1 -> {
errorCallback.onError(error1);
mQueue.next();
}, errorCode);
});
return;
}
errorCallback.onError(error);
mQueue.next();
}));
this.upgradeKVV(successKVV -> {
this.upgradeBB(successKVV, success -> {
if (this.mModules == null)
this.mModules = success;
else if (this.mModules.updateList(success)) {
mListener.onModuleListChange();
store();
}
callback.onResponse(this.mModules);
mQueue.next();
}, errorFunc.apply(Login.LOGOUT_BB));
}, errorFunc.apply(Login.LOGOUT_KVV));
});
});
}
private void upgradeKVV(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
NetworkCallback<Modules> successCallback = (modules -> {
try {
cacheKVVCourse().save(getContext());
} catch (IOException e) {
e.printStackTrace();
}
callback.onResponse(modules);
});
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null) {
errorCallback.onError(new NetworkError(101110, 500, "Currently running in offline mode!"));
private void upgrade(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
log.d(mLogin.isInOnlineMode(), mLogin.getLoginToken());
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101105, 500, "Currently running in offline mode!"));
return;
}
Modules modules = new Modules(mLogin.getLoginTokenKVV().getUsername());
if (!mLogin.getLoginTokenKVV().isAvailable()) {
callback.onResponse(modules);
return;
}
get(Constants.KVV_SERVER_URL+"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
get("https://kvv.imp.fu-berlin.de/direct/site.json", mLogin.getLoginToken().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101111, 403, "No membership list retrieved!"));
errorCallback.onError(new NetworkError(101101, 403, "No module list retrieved!"));
return;
}
JSONArray memberships;
Modules modules = new Modules(mLogin.getLoginToken().getUsername());
JSONArray sites;
try {
JSONObject json = new JSONObject(body);
memberships = json.getJSONArray("membership_collection");
sites = json.getJSONArray("site_collection");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101112, 403, "Cannot parse membership list!"));
errorCallback.onError(new NetworkError(101102, 403, "Cannot parse module list!"));
return;
}
final int[] latch = {memberships.length()};
if (latch[0] == 0) {
successCallback.onResponse(modules);
return;
}
for (int i = 0; i < memberships.length(); i++) {
for (int i = 0; i < sites.length(); i++) {
try {
JSONObject membership = memberships.getJSONObject(i);
String locationReference = membership.getString("locationReference");
String courseId = Regex.regex("/site/([^/]*)", locationReference);
Modules.Module kvvCourse = cacheKVVCourse().getKVVCourse(courseId);
if (kvvCourse != null) {
kvvCourse = kvvCourse.clone();
modules.addModule(kvvCourse);
if (--latch[0] == 0) successCallback.onResponse(modules);
JSONObject site = sites.getJSONObject(i);
String semester_string = site.getJSONObject("props").optString("term_eid", null);
if (semester_string == null)
continue;
Semester semester = new Semester(semester_string);
HashSet<String> lvNumbers = new HashSet<>();
String kvv_lvnumbers = site.getJSONObject("props").optString("kvv_lvnumbers", null);
if (kvv_lvnumbers != null) for (MatchResult matchResult : Regex.allMatches("[0-9]+", kvv_lvnumbers)) {
lvNumbers.add(matchResult.group());
}
get(String.format(Constants.KVV_SERVER_URL+"direct/site/%s.json?_validateSession=", courseId), mLogin.getLoginTokenKVV().getCookies(), response1 -> {
String body1 = response1.getParsed();
if (body1 == null) {
errorCallback.onError(new NetworkError(101113, 403, "No site retrieved!"));
return;
}
try {
JSONObject site = new JSONObject(body1);
String semester_string = site.getJSONObject("props").optString("term_eid", null);
Semester semester;
if (semester_string == null)
semester = null;
else
semester = new Semester(semester_string);
HashSet<String> lvNumbers = new HashSet<>();
String kvv_lvnumbers = site.getJSONObject("props").optString("kvv_lvnumbers", null);
if (kvv_lvnumbers != null)
for (MatchResult matchResult : Regex.allMatches("[0-9]+", kvv_lvnumbers)) {
lvNumbers.add(matchResult.group());
}
String title = site.getString("entityTitle");
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
String kvv_lecturers = site.getJSONObject("props").optString("kvv_lecturers", null);
if (kvv_lecturers != null) for (String lecturer : kvv_lecturers.split("#")) {
if (lecturer.length() > 2)
lecturers.add(new Lecturer(lecturer));
}
String type = site.getJSONObject("props").optString("kvv_coursetype", "Projekt");
String description = site.optString("description", "");
description = String.valueOf(PartModules.fromHtml(description));
String id = site.getString("id");
Modules.Module module = modules.addModule(semester, lvNumbers, title, lecturers, type, description, id, Modules.TYPE_KVV);
cacheKVVCourse().setKVVCourse(courseId, module.clone());
if (--latch[0] == 0) successCallback.onResponse(modules);
} catch (JSONException e) {
log.e(new NetworkError(101114, 403, "Cannot parse site!"));
log.e("JSON:", body1);
e.printStackTrace();
} catch (NoSuchFieldException e) {
log.e(new NetworkError(101115, 403, "Cannot parse site!"));
e.printStackTrace();
}
}, error -> errorCallback.onError(new NetworkError(101116, error.networkResponse.statusCode, "Cannot get parse!")));
String title = site.getString("entityTitle");
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
String kvv_lecturers = site.getJSONObject("props").optString("kvv_lecturers", null);
if (kvv_lecturers != null) for (String lecturer : kvv_lecturers.split("#")) {
if (lecturer.length() > 2)
lecturers.add(new Lecturer(lecturer));
}
String type = site.getJSONObject("props").optString("kvv_coursetype", null);
String description = site.optString("description", "");
description = String.valueOf(PartModules.fromHtml(description));
String id = site.getString("id");
modules.addModule(semester, lvNumbers, title, lecturers, type, description, id);
} catch (JSONException e) {
log.e("ID:", i, "JSON:", memberships);
log.e(new NetworkError(101103, 403, "Cannot parse module list!"));
log.e("ID:", i, "JSON:", sites);
e.printStackTrace();
errorCallback.onError(new NetworkError(101117, 403, "Cannot parse membership list!"));
return;
} catch (NoSuchFieldException e) {
log.e("ID:", i, "JSON:", memberships);
e.printStackTrace();
errorCallback.onError(new NetworkError(101118, 403, "Cannot parse membership list!"));
return;
}
}
}, error -> errorCallback.onError(new NetworkError(101119, error.networkResponse.statusCode, "Cannot get membership list!")));
}
private void upgradeBB(final Modules modulesKVV, final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
NetworkCallback<Modules> successCallback = (modules -> {
try {
cacheBBCourse().save(getContext());
} catch (IOException e) {
e.printStackTrace();
}
callback.onResponse(modules);
});
NetworkCallback<Modules> fastCallback = (modules -> {
mListener.onModuleListPartiallyUpdated(modules);
try {
cacheBBCourse().save(getContext());
} catch (IOException e) {
e.printStackTrace();
}
mListener.onModuleListPartiallyUpdated(modules);
});
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null) {
errorCallback.onError(new NetworkError(101120, 500, "Currently running in offline mode!"));
return;
}
if (!mLogin.getLoginTokenBB().isAvailable()) {
callback.onResponse(modulesKVV);
return;
}
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/users/%s/courses?fields=courseId,dataSourceId", mLogin.getLoginTokenBB().getId()), mLogin.getLoginTokenBB().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101121, 403, "No module list retrieved!"));
return;
}
final JSONArray[] sites = new JSONArray[1];
try {
JSONObject json = new JSONObject(body);
sites[0] = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101122, 403, "Cannot parse module list!"));
return;
}
final int[] latch = {sites[0].length()};
// fetching lecturers takes a lot of time, send success twice: first without lecturers
final int[] latchNoLecturers = {sites[0].length()};
if (sites[0].length() == 0) {
successCallback.onResponse(modulesKVV);
return;
}
for (int i = 0; i < sites[0].length(); i++) {
try {
JSONObject site = sites[0].getJSONObject(i);
String courseId = site.getString("courseId");
if (cacheBBCourse().hasKVVCourseID(courseId)) {
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
continue;
}
Modules.Module bbCourse = cacheBBCourse().getBBCourse(courseId);
if (bbCourse != null) {
bbCourse = bbCourse.clone();
modulesKVV.addModule(bbCourse);
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
continue;
}
get(String.format("https://lms.fu-berlin.de/learn/api/v1/courses/%s?fields=name,courseId,description", courseId), mLogin.getLoginTokenBB().getCookies(), response1 -> {
String body1 = response1.getParsed();
if (body1 == null) {
errorCallback.onError(new NetworkError(101124, 403, "No course entry retrieved!"));
return;
}
try {
JSONObject json = new JSONObject(body1);
String name = json.getString("name");
String description = json.optString("description", null);
String type, lvNumber, semYear, semType;
Semester semester = null;
HashSet<String> lvNumberSet = new HashSet<>();
boolean found = false;
try {
Matcher match = Regex.match("[A-Za-z0-9]*_([A-Za-z0-9]*)_([A-Za-z0-9]*)_([0-9]{2,})([WS]+)", json.getString("courseId"));
type = match.group(1);
lvNumber = match.group(2);
semYear = match.group(3);
semType = match.group(4);
semester = new Semester(semType.equals("W") ? Semester.SEM_WS : Semester.SEM_SS, Integer.valueOf(semYear) % 100);
lvNumberSet.add(lvNumber);
for (Modules.Module module: modulesKVV) {
if (module.lvNumber.contains(lvNumber)) {
found = true;
break;
}
}
} catch (NoSuchFieldException | NumberFormatException e) {
log.e(e);
type = "Projekt";
}
if (!found) {
Modules.Module module = modulesKVV.addModule(semester, lvNumberSet, name, new LinkedHashSet<>(), type, description, courseId, Modules.TYPE_BB);
lecturer().getBBLecturers(courseId, success -> {
module.setLecturers(success);
cacheBBCourse().setBBCourse(courseId, module.clone());
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
}, error -> {
log.e(error);
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
});
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
} else {
cacheBBCourse().addKVVCourseID(courseId);
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
}
} catch (JSONException e) {
e.printStackTrace();
log.e(new NetworkError(101125, 403, "Cannot parse course entry!"));
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
}
}, error -> errorCallback.onError(new NetworkError(101126, error.networkResponse.statusCode, "Cannot get module list!")));
} catch (JSONException e) {
log.e(new NetworkError(101123, 403, "Cannot parse course entry"));
log.e("ID:", i, "JSON:", sites[0]);
log.e(new NetworkError(101106, 403, "Cannot parse module list!"));
log.e("ID:", i, "JSON:", sites);
e.printStackTrace();
}
}
}, error -> errorCallback.onError(new NetworkError(101125, error.networkResponse.statusCode, "Cannot get module list!")));
}
private ModulesListLecturer lecturer() {
if (mLecturer == null)
mLecturer = new ModulesListLecturer(getContext(), mLogin);
return mLecturer;
}
private CacheBBCourse cacheBBCourse() {
if (mBBCache == null) {
try {
mBBCache = CacheBBCourse.load(getContext());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
if (mBBCache == null)
mBBCache = new CacheBBCourse();
return mBBCache;
}
private CacheKVVCourse cacheKVVCourse() {
if (mKVVCache == null) {
try {
mKVVCache = CacheKVVCourse.load(getContext());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
if (mKVVCache == null)
mKVVCache = new CacheKVVCourse();
return mKVVCache;
// Empty module *may be* because token is invalid -> check
if (modules.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(modules), errorCallback);
else
callback.onResponse(modules);
}, error -> errorCallback.onError(new NetworkError(101104, error.networkResponse.statusCode, "Cannot get module list!")));
}
}

View File

@@ -1,157 +0,0 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import de.sebse.fuplanner.services.kvv.types.CacheLecturer;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
class ModulesListLecturer extends HTTPService {
private final Login mLogin;
private final CacheLecturer mStorage;
ModulesListLecturer(Context context, Login login) {
super(context);
this.mLogin = login;
CacheLecturer storage = null;
try {
storage = CacheLecturer.load(context);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (storage == null) {
mStorage = new CacheLecturer();
} else {
mStorage = storage;
}
}
void getBBLecturers(String moduleID, NetworkCallback<LinkedHashSet<Lecturer>> callback, NetworkErrorCallback errorCallback) {
ArrayList<String> lecturerString = mStorage.getLecturersPerCourse(moduleID);
if (lecturerString != null) {
final int[] latch = {lecturerString.size()};
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
for (String userId : lecturerString) {
getBBLecturer(userId, success -> {
lecturers.add(success);
if (--latch[0] == 0) callback.onResponse(lecturers);
}, error -> {
log.e(error);
if (--latch[0] == 0) callback.onResponse(lecturers);
});
}
if (lecturerString.size() == 0)
callback.onResponse(lecturers);
return;
}
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(102100, 500, "Currently running in offline mode!"));
return;
}
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/users?fields=userId,courseRoleId", moduleID), mLogin.getLoginTokenBB().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(102101, 403, "No lecturers retrieved!"));
return;
}
JSONArray sites;
try {
JSONObject json = new JSONObject(body);
sites = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(102102, 403, "Cannot parse lecturers!"));
return;
}
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
final int[] latch = {sites.length()};
ArrayList<String> lecturerString2 = new ArrayList<>();
NetworkCallback<LinkedHashSet<Lecturer>> successCallback = l -> {
mStorage.setLecturersPerCourse(moduleID, lecturerString2);
try {
mStorage.save(getContext());
} catch (IOException e) {
e.printStackTrace();
}
callback.onResponse(lecturers);
};
for (int i = 0; i < sites.length(); i++) {
try {
JSONObject lecturerJson = sites.getJSONObject(i);
String userId = lecturerJson.getString("userId");
String role = lecturerJson.getString("courseRoleId");
if (!"Student".equals(role)) {
lecturerString2.add(userId);
getBBLecturer(userId, success -> {
lecturers.add(success);
if (--latch[0] == 0) successCallback.onResponse(lecturers);
}, error -> {
log.e(error);
if (--latch[0] == 0) successCallback.onResponse(lecturers);
});
} else {
if (--latch[0] == 0) successCallback.onResponse(lecturers);
}
} catch (JSONException e) {
log.e(new NetworkError(102103, 403, "Cannot parse lecturers!"));
log.e("ID:", i, "JSON:", sites);
e.printStackTrace();
if (--latch[0] == 0) successCallback.onResponse(lecturers);
}
}
}, error -> errorCallback.onError(new NetworkError(102104, error.networkResponse.statusCode, "Error retrieving lecturers!")));
}
private void getBBLecturer(String lecturerID, NetworkCallback<Lecturer> callback, NetworkErrorCallback errorCallback) {
Lecturer lecturerStore = mStorage.getLecturer(lecturerID);
if (lecturerStore != null) {
callback.onResponse(lecturerStore);
return;
}
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(102110, 500, "Currently running in offline mode!"));
return;
}
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/users/%s?fields=userName,name", lecturerID), mLogin.getLoginTokenBB().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(102111, 403, "No lecturer retrieved!"));
return;
}
try {
JSONObject json = new JSONObject(body);
String userName = json.getString("userName");
String givenName = json.getJSONObject("name").getString("given");
String familyName = json.getJSONObject("name").getString("family");
Lecturer lecturer = new Lecturer(givenName, familyName, userName + "@zedat.fu-berlin.de", true);
mStorage.setLecturer(lecturerID, lecturer);
try {
mStorage.save(getContext());
} catch (IOException e) {
e.printStackTrace();
}
callback.onResponse(lecturer);
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(102112, 403, "Cannot parse lecturer!"));
}
}, error -> errorCallback.onError(new NetworkError(102113, error.networkResponse.statusCode, "Error retrieving lecturer!")));
}
}

View File

@@ -1,7 +1,6 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import org.json.JSONArray;
@@ -10,9 +9,6 @@ import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import de.sebse.fuplanner.services.kvv.types.Modules;
@@ -42,12 +38,12 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
}
@Override
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Resource>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Resource>> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format("https://kvv.imp.fu-berlin.de/direct/content/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101601, 403, "No resources retrieved!"));
@@ -99,141 +95,23 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
} else {
// in sub folder
for (Resource res2: resources) {
try {
String utf8Name;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
utf8Name = StandardCharsets.UTF_8.name();
else utf8Name = "UTF-8";
if (URLDecoder.decode(res2.getUrl(), utf8Name).endsWith(res.getContainer()) && res2 instanceof Resource.Folder) {
// Append File/Folder to list
((Resource.Folder) res2).add(res);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
if (res2.getUrl().endsWith(res.getContainer()) && res2 instanceof Resource.Folder) {
// Append File/Folder to list
((Resource.Folder) res2).add(res);
}
}
}
}
}
callback.onResponse(root);
// Empty resources *may be* because token is invalid -> check
if (resources.size() == 0)
mLogin.testLoginToken(token -> callback.onResponse(root), errorCallback);
else
callback.onResponse(root);
}, error -> errorCallback.onError(new NetworkError(101603, error.networkResponse.statusCode, "Cannot get resources!")));
}
@Override
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Resource>> callback, NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101614, 500, "Currently running in offline mode!"));
return;
}
getRescourceFolder(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/", ID), ID, false, callback, errorCallback);
//callback.onResponse(new ArrayList<>());
}
private void getRescourceFolder(String url, String ID, boolean subRequest, NetworkCallback<ArrayList<Resource>> callback, NetworkErrorCallback errorCallback) {
if (mLogin.getLoginTokenBB() == null) {
errorCallback.onError(new NetworkError(101610, 500, "Cannot get resources!"));
return;
}
get(url, mLogin.getLoginTokenBB().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101611, 403, "No resources retrieved!"));
return;
}
ArrayList<Resource> resources = new ArrayList<>();
JSONArray sites;
try {
JSONObject json = new JSONObject(body);
sites = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101612, 400, "Cannot parse resources!"));
return;
}
final int[] latch = {sites.length()};
for (int i = 0; i < sites.length(); i++) {
try {
JSONObject resource = sites.getJSONObject(i);
String resid = resource.getString("id");
String title = resource.getString("title");
String created = resource.getString("created");
String content = resource.getJSONObject("contentHandler").getString("id");
long createdDate = UtilsDate.stringToMillis(created, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
if (content.equals("resource/x-bb-folder")) {
String url2 = String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s", ID, resid);
Resource.Folder folder = new Resource.Folder("", title, createdDate, url2, true, "");
resources.add(folder);
getRescourceFolder(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s/children", ID, resid), ID, true, response1 -> {
for (Resource resource1 : response1) {
folder.add(resource1);
}
if (--latch[0] == 0) callback.onResponse(resources);
}, error -> {
if (error.getHttpStatus() == 403) {
if (--latch[0] == 0) callback.onResponse(resources);
} else {
errorCallback.onError(error);
}
});
} else {
String bodyText = resource.optString("body", "");
bodyText = String.valueOf(PartModules.fromHtml(bodyText));
String url2 = String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s", ID, resid);
Resource.Document document = new Resource.Document("", title, createdDate, url2, true, "", bodyText);
resources.add(document);
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s/attachments", ID, resid), mLogin.getLoginTokenBB().getCookies(), response1 -> {
String body1 = response1.getParsed();
if (body1 == null) {
errorCallback.onError(new NetworkError(101617, 403, "No resource attachments retrieved!"));
return;
}
JSONArray attachments;
try {
JSONObject json = new JSONObject(body1);
attachments = json.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(101618, 400, "Cannot parse resource attachments!"));
return;
}
for (int j = 0; j < attachments.length(); j++) {
try {
JSONObject attachment = attachments.getJSONObject(j);
String attachid = attachment.getString("id");
String attachname = attachment.getString("fileName");
document.addUrl(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s/attachments/%s/download", ID, resid, attachid), attachname);
} catch (JSONException e) {
log.e(new NetworkError(101619, 400, "Cannot parse resource attachments!"));
e.printStackTrace();
log.e("ID:", j, "JSON:", attachments);
}
}
if (--latch[0] == 0) callback.onResponse(resources);
}, error -> errorCallback.onError(new NetworkError(101616, error.networkResponse.statusCode, "Cannot get resource attachments!")));
}
} catch (JSONException e) {
log.e(new NetworkError(101615, 400, "Cannot parse resources!"));
e.printStackTrace();
log.e("ID:", i, "JSON:", sites);
}
}
}, error -> {
if (error.networkResponse.statusCode != 403) {
errorCallback.onError(new NetworkError(101613, error.networkResponse.statusCode, "Cannot get resources!"));
} else {
callback.onResponse(new ArrayList<>());
}
});
}
@@ -258,11 +136,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
return;
}
}
fileUpgrade(filename, url, modulename, callback, error -> {
fileUpgrade(filename, url , modulename, callback, error -> {
if (retries >= 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
mLogin.refreshLogin(success -> {
file(filename, url, modulename, callback, errorCallback, forceRefresh, retries-1);
}, errorCallback, url.contains("lms.fu-berlin.de") ? Login.LOGOUT_BB : Login.LOGOUT_KVV);
}, errorCallback);
return;
}
errorCallback.onError(error);
@@ -270,19 +148,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
}
private void fileUpgrade(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
if (url.contains("lms.fu-berlin.de")) {
fileUpgradeBB(filename, url, modulename, callback, errorCallback);
} else {
fileUpgradeKVV(filename, url, modulename, callback, errorCallback);
}
}
private void fileUpgradeKVV(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
return;
}
get(url, mLogin.getLoginTokenKVV().getCookies(), response -> {
get(url, mLogin.getLoginToken().getCookies(), response -> {
if (Regex.has("\\.[Uu][Rr][Ll]$", url)){
// Return redirected URL
String path = response.getHeaders().get("Location");
@@ -296,50 +166,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
String path = saveFileInDownloads(filename, response.getBytes(), modulename);
callback.onResponse(path);
} else {
errorCallback.onError(new NetworkError(101704, 400, "External storage not writable!"));
errorCallback.onError(new NetworkError(101704, 403, "External storage not writable!"));
}
}, error -> errorCallback.onError(new NetworkError(101702, error.networkResponse.statusCode, "Cannot get file!")));
}
private void fileUpgradeBB(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101615, 500, "Currently running in offline mode!"));
return;
}
get(url, mLogin.getLoginTokenBB().getCookies(), response -> {
if (response.getHeaders().containsKey("Location")) {
// Return redirected URL
String redirectUrl = response.getHeaders().get("Location");
if (redirectUrl == null){
redirectUrl = "";
}
get(redirectUrl, mLogin.getLoginTokenBB().getCookies(), response1 -> {
if (response1.getHeaders().containsKey("Location")) {
// Return redirected URL
String redirectUrl2 = response1.getHeaders().get("Location");
if (redirectUrl2 == null) {
redirectUrl2 = "";
} else {
redirectUrl2 = "https://lms.fu-berlin.de" + redirectUrl2;
}
get(redirectUrl2, mLogin.getLoginTokenBB().getCookies(), response2 -> {
if (response2.getBytes() == null) {
errorCallback.onError(new NetworkError(101714, 400, "Cannot get file!"));
} else if (isExternalStorageWritable()) {
String path = saveFileInDownloads(filename, response2.getBytes(), modulename);
callback.onResponse(path);
} else {
errorCallback.onError(new NetworkError(101713, 400, "External storage not writable!"));
}
}, error -> errorCallback.onError(new NetworkError(101717, error.networkResponse.statusCode, "Cannot get file!")));
} else {
errorCallback.onError(new NetworkError(101716, 400, "External storage not writable!"));
}
}, error -> errorCallback.onError(new NetworkError(101712, error.networkResponse.statusCode, "Cannot get file!")));
} else {
errorCallback.onError(new NetworkError(101711, 400, "External storage not writable!"));
}
}, error -> errorCallback.onError(new NetworkError(101710, error.networkResponse.statusCode, "Cannot get file!")));
}
@@ -372,7 +203,7 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
// Saves file in folder: DOWNLOADS/moduleName
File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), moduleName);
if (!folder.mkdirs()) {
if (!folder.mkdir()) {
log.w( "Directory not created");
}
String path = "";

View File

@@ -19,22 +19,13 @@ abstract class PartModules<T> extends Part<Modules.Module> {
@Override
protected void recv(final Modules.Module module, final NetworkCallback<Modules.Module> callback, final NetworkErrorCallback errorCallback, final boolean forceRefresh, final int retries) {
mQueue.add(() -> {
if (mLogin.isLoginPending()) {
mLogin.restoreOnlineLogin(resCode -> {
mQueue.next();
});
} else {
mQueue.next();
}
});
mQueue.add(() -> {
if (getPart(module) != null && !forceRefresh) {
callback.onResponse(module);
mQueue.next();
return;
}
upgrade(module.getModuleType(), module.getID(), success -> {
upgrade(module.getID(), success -> {
if (setPart(module, success)) {
this.mList.store();
}
@@ -48,7 +39,7 @@ abstract class PartModules<T> extends Part<Modules.Module> {
}, error1 -> {
errorCallback.onError(error1);
mQueue.next();
}, module.getModuleType() == Modules.TYPE_BB ? Login.LOGOUT_BB : Login.LOGOUT_KVV);
});
return;
}
errorCallback.onError(error);
@@ -70,18 +61,5 @@ abstract class PartModules<T> extends Part<Modules.Module> {
protected abstract boolean setPart(Modules.Module module, T part);
protected void upgrade(final int moduleType, final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback) {
switch (moduleType) {
case Modules.TYPE_KVV:
upgradeKVV(ID, callback, errorCallback);
break;
case Modules.TYPE_BB:
upgradeBB(ID, callback, errorCallback);
break;
}
}
protected abstract void upgradeKVV(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
protected abstract void upgradeBB(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
protected abstract void upgrade(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
}

View File

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

View File

@@ -1,143 +0,0 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class FULogin extends HTTPService {
public FULogin(Context context) {
super(context);
}
public void fulogin(String requestURI, String username, String password, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
String old_shib_idp_session = Preferences.getString(getContext(), R.string.pref_shib_idp_session);
step2(requestURI, old_shib_idp_session, success2 -> {
String samlResp = success2.get("SAMLResponse");
if (samlResp != null) {
callback.onResponse(samlResp);
return;
}
String fuJSESSIONID = success2.get("JSESSIONID");
step3(fuJSESSIONID, success3 -> {
step4(username, password, fuJSESSIONID, success4 -> {
String shib_idp_session = success4.get("shib_idp_session");
Preferences.setString(getContext(), R.string.pref_shib_idp_session, shib_idp_session);
String samlResponse = success4.get("SAMLResponse");
if (samlResponse != null)
callback.onResponse(samlResponse);
else
errorCallback.onError(new NetworkError(100300, -1, "Cannot get SAML Response!"));
}, errorCallback);
}, errorCallback);
}, errorCallback);
}
/*
2= GET [Location-Header 1]
-> Set-Cookie: JSESSIONID=[JSESSION-FU]
-> Location: /idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1
*/
private void step2(String url, @Nullable String shib_idp_session, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookiesReq = null;
if (shib_idp_session != null) {
cookiesReq = new HashMap<>();
cookiesReq.put("shib_idp_session", shib_idp_session);
}
get(url, cookiesReq, response -> {
String body = response.getParsed();
if (body != null) {
Pattern pattern = Pattern.compile("name=\"SAMLResponse\" value=\"([0-9a-zA-Z+]+=*)");
Matcher matcher = pattern.matcher(body);
if (!matcher.find()) {
errorCallback.onError(new NetworkError(100344, -1, "Error on getting SAML response!"));
return;
}
HashMap<String, String> object = new HashMap<>();
object.put("SAMLResponse", matcher.group(1));
callback.onResponse(object);
return;
}
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies == null) {
errorCallback.onError(new NetworkError(100321, -1, "Error on starting FU session!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies, new String[]{"JSESSIONID"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100322, -1, "Error on starting FU session!"));
return;
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100320, error.networkResponse.statusCode, "Error on starting FU session!")));
}
/*
3= GET [Location-Header 2]
+ Cookie: JSESSIONID=[JSESSION-FU]
*/
private void step3(String JSESSIONID_FU, final NetworkCallback<Boolean> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID_FU);
head("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookies, response -> {
callback.onResponse(true);
}, error -> errorCallback.onError(new NetworkError(100330, error.networkResponse.statusCode, "Error starting login page!")));
}
/*
4= POST [Location-Header 2]
+ Body: j_username=[USERNAME]&j_password=[PASSWORD]&_eventId_proceed=
+ Header: Content-Type: application/x-www-form-urlencoded
+ Header: Referer: [Location-Header 2]
+ Cookie: JSESSIONID=[JSESSION-FU]
-> Set-Cookie: shib_idp_session=[SHIB-IDP-SESSION]
-> Body SAMLResponse-Input-value
*/
private void step4(String username, String password, String JSESSIONID_FU, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID_FU);
HashMap<String, String> body = new HashMap<>();
body.put("j_username", username);
body.put("j_password", password);
body.put("_eventId_proceed", "");
post("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookies, body, response -> {
String content = response.getParsed();
if (content == null) {
errorCallback.onError(new NetworkError(100343, -1, "Error on getting SAML response!"));
return;
}
String cookies1 = response.getHeaders().get("Set-Cookie");
if (cookies1 ==null) {
errorCallback.onError(new NetworkError(100341, -1, "Error on logging in to FU Identity Server!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies1, new String[]{"shib_idp_session"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100342, -1, "Error on logging in to FU Identity Server!"));
return;
}
Pattern pattern = Pattern.compile("name=\"SAMLResponse\" value=\"([0-9a-zA-Z+]+=*)");
Matcher matcher = pattern.matcher(content);
if (!matcher.find()) {
errorCallback.onError(new NetworkError(100344, -1, "Error on getting SAML response!"));
return;
}
object.put("SAMLResponse", matcher.group(1));
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100345, error.networkResponse.statusCode, "Error on logging in to FU Identity Server!")));
}
}

View File

@@ -11,7 +11,7 @@ import androidx.annotation.Nullable;
public class KVVContentProvider extends ContentProvider {
public static final String PROVIDER_NAME = "de.sebse.fuplanner.contentprovider.kvv.modules";
private static final String PROVIDER_NAME = "de.sebse.fuplanner.contentprovider.kvv.modules";
private static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/modules");
private static final int MODULE = 1;
private static final int MODULE_ID = 2;

View File

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

View File

@@ -3,71 +3,30 @@ package de.sebse.fuplanner.services.kvv.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.IBinder;
import java.util.ArrayList;
import com.android.volley.NetworkResponse;
import java.util.Iterator;
import androidx.annotation.StringRes;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.fragments.moddetails.ModulePart;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Assignment;
import de.sebse.fuplanner.services.kvv.types.AssignmentList;
import de.sebse.fuplanner.services.kvv.types.EventList;
import de.sebse.fuplanner.services.kvv.types.Grade;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.kvv.types.Resource;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.CustomNotificationManager;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import static de.sebse.fuplanner.MainActivity.FRAGMENT_MODULES_DETAILS;
public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
private KVV mKVV;
private Logger log = new Logger(this);
private NewAsyncQueue mQueue = new NewAsyncQueue();
private boolean mBound = false;
private boolean mWaitForBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
KVV.LocalBinder binder = (KVV.LocalBinder) service;
mKVV = binder.getService();
mBound = true;
if (mWaitForBound) {
mWaitForBound = false;
mQueue.next();
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mKVV = null;
}
};
/**
* Set up the sync adapter
*/
KVVSyncAdapter(Context context, boolean autoInitialize) {
public KVVSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
init(context);
}
@@ -85,7 +44,16 @@ public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
}
private void init(Context context) {
// Bind to LocalService
mKVV = new KVV(new KVVListener() {
CustomAccountManager accountManager = null;
@Override
public CustomAccountManager getAccountManager() {
if (accountManager == null)
accountManager = new CustomAccountManager(AccountManager.get(context), () -> null);
return accountManager;
}
}, context);
mKVV.account().restoreOnlineLogin(bool -> {});
}
/*
@@ -100,105 +68,20 @@ public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
String authority,
ContentProviderClient provider,
SyncResult syncResult) {
if (!mBound) {
Intent intent = new Intent(getContext(), KVV.class);
mWaitForBound = true;
mQueue.add(() -> {});
}
mQueue.add(() -> {
mKVV.account().restoreOnlineLogin(bool -> {
mQueue.next();
});
});
mQueue.add(() -> {
if (!mKVV.account().isLoggedIn()) {
log.w("Not logged in!");
return;
log.d("start syncing");
/*
* Put the data transfer code here.
*/
mKVV.modules().list().recv(success -> {
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
Modules.Module module = iterator.next();
log.d("sync module", module.title);
mKVV.modules().details().recv(module, success1 -> {
if (success1.second)
log.d("Sync Successful for Module '"+module.title+"'!");
}, log::e, true);
}
mKVV.modules().list().reloadIfOutdated();
mKVV.modules().list().recv(success -> {
final int[] latch = {0};
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
latch[0] += 1;
iterator.next();
}
iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
Modules.Module module = iterator.next();
final ArrayList<Announcement> announcements = module.announcements;
final AssignmentList assignments = module.assignments;
final EventList events = module.events;
final ArrayList<Grade> gradebook = module.gradebook;
final ArrayList<Resource> resources = module.resources;
mKVV.modules().details().recv(module, success1 -> {
if (success1.second) {
sendNotifications(announcements, module.announcements, module.title, Announcement::getTitle, Announcement::getId,
module.getID(), ModulePart.ANNOUNCEMENT,
R.string.announcement_updated, R.string.announcement_added, R.string.announcement_removed);
sendNotifications(assignments, module.assignments, module.title, Assignment::getTitle, Assignment::getId,
module.getID(), ModulePart.ASSIGNMENT,
R.string.assignment_updated, R.string.assignment_added, R.string.assignment_removed);
sendNotifications(events, module.events, module.title, evt -> evt.getTitle()+" - "+UtilsDate.getModifiedDate(evt.getStartDate()), event -> String.valueOf(event.getStartDate())+event.getType()+event.getTitle(),
module.getID(), ModulePart.EVENT,
R.string.event_updated, R.string.event_added, R.string.event_removed);
sendNotifications(gradebook, module.gradebook, module.title, Grade::getItemName, Grade::getItemName,
module.getID(), ModulePart.GRADEBOOK,
R.string.gradebook_updated, R.string.gradebook_added, R.string.gradebook_removed);
sendNotifications(resources, module.resources, module.title, Resource::getTitle, Resource::getUrl,
module.getID(), ModulePart.RESOURCES,
R.string.resource_updated, R.string.resource_added, R.string.resource_removed);
if (--latch[0] == 0) mQueue.next();
}
}, error -> {
log.e(error);
if (--latch[0] == 0) mQueue.next();
}, true);
}
}, msg -> {
log.e(msg);
mQueue.next();
}, true);
});
mQueue.add(() -> {
mBound = false;
mKVV = null;
getContext().unbindService(mConnection);
});
}
private <T> void sendNotifications(Iterable<T> oldList, Iterable<T> newList, String title, StringInterface<T> titleInterface, StringInterface<T> idInterface, String moduleId, int modulePart, @StringRes int updateRes, @StringRes int addRes, @StringRes int removeRes) {
if (oldList == null || newList == null) {
return;
}
ArrayList<T> obsoletes = new ArrayList<>();
for (T old: oldList) {
obsoletes.add(old);
}
String targetData = moduleId+"."+ModulePart.getPageByPart(modulePart);
for (T newEntry: newList) {
boolean found = false;
for (T oldEntry: oldList) {
if (idInterface.get(newEntry).equals(idInterface.get(oldEntry))) {
found = true;
if (newEntry.hashCode() != oldEntry.hashCode()) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(updateRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
obsoletes.remove(oldEntry);
break;
}
}
if (!found) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(addRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
}
for (T oldEntry: obsoletes) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(removeRes, title), titleInterface.get(oldEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
}
@FunctionalInterface
interface StringInterface<T> {
String get(T element);
}, log::e, true);
}
}

View File

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

View File

@@ -2,12 +2,16 @@ package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashSet;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.tools.UtilsJson;
public class Announcement implements Serializable {
public class Announcement implements UtilsJson.JsonConvertible {
private final String id;
private final String title;
private final String body;
@@ -24,11 +28,24 @@ public class Announcement implements Serializable {
this.urls = urls;
}
public Announcement(JSONObject json) throws JSONException {
this.id = json.getString("id");
this.title = json.getString("title");
this.body = json.getString("body");
this.createdBy = json.getString("createdBy");
this.createdOn = json.getLong("createdOn");
ArrayList<String> urls = new ArrayList<>();
for (String url: UtilsJson.jsonArrayToIterableString(json.getJSONArray("urls"))) {
urls.add(url);
}
this.urls = urls;
}
public ArrayList<String> getUrls() {
return urls;
}
public String getId() {
private String getId() {
return id;
}
@@ -63,4 +80,16 @@ public class Announcement implements Serializable {
public int hashCode() {
return Objects.hashCode(getId(), getBody(), getCreatedBy(), getCreatedOn(), getTitle(), getUrls());
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("id", id);
json.put("title", title);
json.put("body", body);
json.put("createdBy", createdBy);
json.put("createdOn", createdOn);
json.put("urls", UtilsJson.collectionToJson(urls));
return json;
}
}

View File

@@ -2,12 +2,15 @@ package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.tools.UtilsJson;
public class Assignment implements Serializable {
public class Assignment implements UtilsJson.JsonConvertible {
private final String id;
private final String title;
private final long dueTime;
@@ -22,7 +25,7 @@ public class Assignment implements Serializable {
this.instructions = instructions;
}
public String getId() {
private String getId() {
return id;
}
@@ -59,4 +62,15 @@ public class Assignment implements Serializable {
public int hashCode() {
return Objects.hashCode(getId(), getDueDate(), getInstructions(), getTitle(), getUrls());
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("id", id);
json.put("title", title);
json.put("dueTime", dueTime);
json.put("createdBy", UtilsJson.collectionToJson(urls));
json.put("instructions", instructions);
return json;
}
}

View File

@@ -1,92 +0,0 @@
package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
public class CacheBBCourse implements Serializable {
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
private static final String FILE_NAME = "BBCourseStorageSaving";
private static final String FILE_NAME_TIMESTAMP = "BBCourseStorageSavingTimestamp";
private transient long mLastTimestamp = 0;
private HashSet<String> mKVVCourseList = new HashSet<>();
private long mKVVCourseListRefresh = 0;
private HashMap<String, Modules.Module> mBBCourseList = new HashMap<>();
private HashMap<String, Long> mBBCourseListRefresh = new HashMap<>();
public static CacheBBCourse load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheBBCourse))
return null;
CacheBBCourse storage = (CacheBBCourse) readObject;
is.close();
fis.close();
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
is = new ObjectInputStream(fis);
storage.mLastTimestamp = is.readLong();
is.close();
fis.close();
return storage;
}
public boolean isNewerVersionInStorage(Context context) throws IOException {
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
ObjectInputStream is = new ObjectInputStream(fis);
boolean result = this.mLastTimestamp < is.readLong();
is.close();
fis.close();
return result;
}
public void save(Context context) throws IOException {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
this.mLastTimestamp = System.currentTimeMillis();
os.writeLong(this.mLastTimestamp);
os.close();
fos.close();
}
public void addKVVCourseID(String courseID) {
mKVVCourseList.add(courseID);
mKVVCourseListRefresh = System.currentTimeMillis();
}
public boolean hasKVVCourseID(String courseID) {
if (mKVVCourseListRefresh + RESAVE_TIMER < System.currentTimeMillis())
return false;
return mKVVCourseList.contains(courseID);
}
public void setBBCourse(String courseID, Modules.Module lecturer) {
mBBCourseList.put(courseID, lecturer);
mBBCourseListRefresh.put(courseID, System.currentTimeMillis());
}
public Modules.Module getBBCourse(String courseID) {
if (!mBBCourseListRefresh.containsKey(courseID))
return null;
//noinspection ConstantConditions
if (mBBCourseListRefresh.get(courseID) + RESAVE_TIMER < System.currentTimeMillis())
return null;
return mBBCourseList.get(courseID);
}
}

View File

@@ -1,78 +0,0 @@
package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
public class CacheBBEventNumber implements Serializable {
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
private static final String FILE_NAME = "BBEventNumberStorageSaving";
private static final String FILE_NAME_TIMESTAMP = "BBEventNumberStorageSavingTimestamp";
private transient long mLastTimestamp = 0;
private HashMap<String, String> mBBEventNumbers = new HashMap<>();
private HashMap<String, Long> mBBEventNumbersRefresh = new HashMap<>();
public static CacheBBEventNumber load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheBBEventNumber))
return null;
CacheBBEventNumber storage = (CacheBBEventNumber) readObject;
is.close();
fis.close();
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
is = new ObjectInputStream(fis);
storage.mLastTimestamp = is.readLong();
is.close();
fis.close();
return storage;
}
public boolean isNewerVersionInStorage(Context context) throws IOException {
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
ObjectInputStream is = new ObjectInputStream(fis);
boolean result = this.mLastTimestamp < is.readLong();
is.close();
fis.close();
return result;
}
public void save(Context context) throws IOException {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
this.mLastTimestamp = System.currentTimeMillis();
os.writeLong(this.mLastTimestamp);
os.close();
fos.close();
}
public void setVVNumber(String lvNumber, String vvNumber) {
mBBEventNumbers.put(lvNumber, vvNumber);
mBBEventNumbersRefresh.put(lvNumber, System.currentTimeMillis());
}
public String getVVNumber(String lvNumber) {
if (!mBBEventNumbersRefresh.containsKey(lvNumber))
return null;
//noinspection ConstantConditions
if (mBBEventNumbersRefresh.get(lvNumber) + RESAVE_TIMER < System.currentTimeMillis())
return null;
return mBBEventNumbers.get(lvNumber);
}
}

View File

@@ -1,79 +0,0 @@
package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
public class CacheKVVCourse implements Serializable {
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
private static final String FILE_NAME = "KVVCourseStorageSaving";
private static final String FILE_NAME_TIMESTAMP = "KVVCourseStorageSavingTimestamp";
private transient long mLastTimestamp = 0;
private HashMap<String, Modules.Module> mKVVCourseList = new HashMap<>();
private HashMap<String, Long> mKVVCourseListRefresh = new HashMap<>();
public static CacheKVVCourse load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheKVVCourse))
return null;
CacheKVVCourse storage = (CacheKVVCourse) readObject;
is.close();
fis.close();
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
is = new ObjectInputStream(fis);
storage.mLastTimestamp = is.readLong();
is.close();
fis.close();
return storage;
}
public boolean isNewerVersionInStorage(Context context) throws IOException {
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
ObjectInputStream is = new ObjectInputStream(fis);
boolean result = this.mLastTimestamp < is.readLong();
is.close();
fis.close();
return result;
}
public void save(Context context) throws IOException {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
this.mLastTimestamp = System.currentTimeMillis();
os.writeLong(this.mLastTimestamp);
os.close();
fos.close();
}
public void setKVVCourse(String courseID, Modules.Module lecturer) {
mKVVCourseList.put(courseID, lecturer);
mKVVCourseListRefresh.put(courseID, System.currentTimeMillis());
}
public Modules.Module getKVVCourse(String courseID) {
if (!mKVVCourseListRefresh.containsKey(courseID))
return null;
//noinspection ConstantConditions
if (mKVVCourseListRefresh.get(courseID) + RESAVE_TIMER < System.currentTimeMillis())
return null;
return mKVVCourseList.get(courseID);
}
}

View File

@@ -1,95 +0,0 @@
package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
public class CacheLecturer implements Serializable {
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
private static final String FILE_NAME = "LecturerStorageSaving";
private static final String FILE_NAME_TIMESTAMP = "LecturerStorageSavingTimestamp";
private transient long mLastTimestamp = 0;
private HashMap<String, ArrayList<String>> mLecturersPerCourse = new HashMap<>();
private HashMap<String, Long> mLecturersPerCourseRefresh = new HashMap<>();
private HashMap<String, Lecturer> mLecturers = new HashMap<>();
private HashMap<String, Long> mLecturersRefresh = new HashMap<>();
public static CacheLecturer load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheLecturer))
return null;
CacheLecturer storage = (CacheLecturer) readObject;
is.close();
fis.close();
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
is = new ObjectInputStream(fis);
storage.mLastTimestamp = is.readLong();
is.close();
fis.close();
return storage;
}
public boolean isNewerVersionInStorage(Context context) throws IOException {
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
ObjectInputStream is = new ObjectInputStream(fis);
boolean result = this.mLastTimestamp < is.readLong();
is.close();
fis.close();
return result;
}
public void save(Context context) throws IOException {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
this.mLastTimestamp = System.currentTimeMillis();
os.writeLong(this.mLastTimestamp);
os.close();
fos.close();
}
public void setLecturersPerCourse(String courseID, ArrayList<String> lecturers) {
mLecturersPerCourse.put(courseID, lecturers);
mLecturersPerCourseRefresh.put(courseID, System.currentTimeMillis());
}
public void setLecturer(String lecturerID, Lecturer lecturer) {
mLecturers.put(lecturerID, lecturer);
mLecturersRefresh.put(lecturerID, System.currentTimeMillis());
}
public ArrayList<String> getLecturersPerCourse(String courseID) {
if (!mLecturersPerCourseRefresh.containsKey(courseID))
return null;
//noinspection ConstantConditions
if (mLecturersPerCourseRefresh.get(courseID) + RESAVE_TIMER < System.currentTimeMillis())
return null;
return mLecturersPerCourse.get(courseID);
}
public Lecturer getLecturer(String lecturerID) {
if (!mLecturersRefresh.containsKey(lecturerID))
return null;
//noinspection ConstantConditions
if (mLecturersRefresh.get(lecturerID) + RESAVE_TIMER < System.currentTimeMillis())
return null;
return mLecturers.get(lecturerID);
}
}

View File

@@ -2,15 +2,18 @@ package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.tools.ColorRGB;
import de.sebse.fuplanner.tools.UtilsJson;
public class Event implements Serializable {
public class Event implements UtilsJson.JsonConvertible {
private final String siteId;
private final String id;
private final String type;
@@ -118,6 +121,19 @@ public class Event implements Serializable {
@Override
public int hashCode() {
return Objects.hashCode(getType(), getStartDate(), getEndDate(), getTitle(), getLocation());
return Objects.hashCode(getId(), getType(), getStartDate(), getEndDate(), getTitle(), getLocation());
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("siteId", siteId);
json.put("id", id);
json.put("type", type);
json.put("title", title);
json.put("duration", duration);
json.put("firstTime", firstTime);
json.put("location", location);
return json;
}
}

View File

@@ -2,11 +2,13 @@ package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.tools.UtilsJson;
public class Grade implements Serializable {
public class Grade implements UtilsJson.JsonConvertible {
private final String itemName;
private final double grade;
private final double maxPoints;
@@ -41,4 +43,13 @@ public class Grade implements Serializable {
public int hashCode() {
return Objects.hashCode(getItemName(), getPoints(), getMaxPoints());
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("itemName", itemName);
json.put("grade", grade);
json.put("maxPoints", maxPoints);
return json;
}
}

View File

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

View File

@@ -1,24 +1,22 @@
package de.sebse.fuplanner.services.kvv.types;
import java.io.Serializable;
import com.google.android.gms.common.internal.Objects;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.tools.UtilsJson;
public class Lecturer implements Serializable {
public class Lecturer implements UtilsJson.JsonConvertible {
private final String firstName;
private final String surname;
private final String mail;
private final boolean isResponsible;
public Lecturer(String firstName, String surname, String mail, boolean isResponsible) {
this.firstName = firstName;
this.surname = surname;
this.mail = mail;
this.isResponsible = isResponsible;
}
public Lecturer(String parsableString) throws NoSuchFieldException {
Pattern pattern = Pattern.compile("([^|]*)\\|([^|]*)\\|([^|]*)\\|\\|([^|]*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(parsableString);
@@ -31,6 +29,13 @@ public class Lecturer implements Serializable {
this.isResponsible = matcher.group(4).equals("true");
}
public Lecturer(JSONObject json) throws JSONException {
this.firstName = json.getString("firstName");
this.surname = json.getString("surname");
this.mail = json.getString("mail");
this.isResponsible = json.getBoolean("isResponsible");
}
public String getFirstName() {
return firstName;
}
@@ -62,4 +67,19 @@ public class Lecturer implements Serializable {
"\nSurname: "+getSurname()+
"\nMail: "+getMail();
}
@Override
public int hashCode() {
return Objects.hashCode(getFirstName(), getSurname(), getMail(), isResponsible());
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("firstName", firstName);
json.put("surname", surname);
json.put("mail", mail);
json.put("isResponsible", isResponsible);
return json;
}
}

View File

@@ -1,34 +1,41 @@
package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.logging.Logger;
/**
* Created by sebastian on 29.10.17.
*/
public class LoginTokenKVV {
public class LoginToken {
private final String username;
private final String shibsessionKey;
private final String shibsessionName;
private final String JSESSIONID;
private boolean isAvailable = true;
@Nullable private String fullName;
@Nullable private String email;
public LoginTokenKVV(String username, String JSESSIONID) {
public LoginToken(String username, String shibsessionKey, String shibsessionName, String JSESSIONID) {
this.username = username;
this.shibsessionKey = shibsessionKey;
this.shibsessionName = shibsessionName;
this.JSESSIONID = JSESSIONID;
}
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
@Nullable
public static void load(CustomAccountManager manager, LoginTokenInterface callback) {
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
callback.run(null);
return;
@@ -38,8 +45,8 @@ public class LoginTokenKVV {
callback.run(null);
return;
}
callback.run(LoginTokenKVV.fromJsonString(tokenString));
}, errorCallback);
callback.run(LoginToken.fromJsonString(tokenString));
});
}
public void delete(CustomAccountManager manager) {
@@ -49,23 +56,20 @@ public class LoginTokenKVV {
public void setAdditionals(String fullName, String email) {
this.fullName = fullName;
this.email = email;
this.isAvailable = true;
}
public void setNotAvailable() {
this.fullName = null;
this.email = null;
this.isAvailable = false;
}
public boolean isAvailable() {
return isAvailable;
}
public String getUsername() {
return username;
}
private String getShibsessionKey() {
return shibsessionKey;
}
private String getShibsessionName() {
return shibsessionName;
}
private String getJSESSIONID() {
return JSESSIONID;
}
@@ -83,6 +87,7 @@ public class LoginTokenKVV {
public HashMap<String, String> getCookies() {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", getJSESSIONID());
cookies.put(getShibsessionKey(), getShibsessionName());
cookies.put("pasystem_timezone_ok", "true");
return cookies;
}
@@ -106,30 +111,30 @@ public class LoginTokenKVV {
JSONObject json = new JSONObject();
try {
json.put("username", username);
json.put("shibsessionKey", shibsessionKey);
json.put("shibsessionName", shibsessionName);
json.put("JSESSIONID", JSESSIONID);
json.put("fullName", fullName);
json.put("email", email);
json.put("isAvailable", isAvailable);
} catch (JSONException e) {
return null;
}
return json.toString();
}
private static LoginTokenKVV fromJsonString(String tokenString) {
public static LoginToken fromJsonString(String tokenString) {
try {
JSONObject json = new JSONObject(tokenString);
LoginTokenKVV token = new LoginTokenKVV(
LoginToken token = new LoginToken(
json.getString("username"),
json.getString("shibsessionName"),
json.getString("shibsessionName"),
json.getString("JSESSIONID"));
if (!json.isNull("fullName"))
token.setAdditionals(
json.getString("fullName"),
json.getString("email")
);
if (!json.optBoolean("isAvailable", true)) {
token.setNotAvailable();
}
return token;
} catch (JSONException e) {
e.printStackTrace();
@@ -137,12 +142,7 @@ public class LoginTokenKVV {
}
}
@Override
public int hashCode() {
return Objects.hashCode(username, JSESSIONID, fullName, email);
}
public interface LoginTokenInterface {
void run(LoginTokenKVV token);
void run(LoginToken token);
}
}

View File

@@ -1,156 +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 LoginTokenBB {
private final String s_session_id;
private final String session_id;
private final String username;
private boolean isAvailable = true;
@Nullable private String id;
@Nullable private String studentId;
public LoginTokenBB(String username, String s_session_id, String session_id) {
this.username = username;
this.s_session_id = s_session_id;
this.session_id = session_id;
}
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
callback.run(null);
return;
}
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, tokenString -> {
if (tokenString == null) {
callback.run(null);
return;
}
callback.run(LoginTokenBB.fromJsonString(tokenString));
}, errorCallback);
}
public void delete(CustomAccountManager manager) {
manager.deleteAccount(AccountGeneral.ACCOUNT_TYPE);
}
public void setAdditionals(String id, String studentId) {
this.id = id;
this.studentId = studentId;
this.isAvailable = true;
}
public void setNotAvailable() {
this.id = null;
this.studentId = null;
this.isAvailable = false;
}
public boolean isAvailable() {
return isAvailable;
}
public String getUsername() {
return username;
}
private String getSessionId() {
return session_id;
}
public String getSSessionId() {
return s_session_id;
}
@Nullable
public String getId() {
return id;
}
@Nullable
public String getStudentId() {
return studentId;
}
public HashMap<String, String> getCookies() {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("session_id", getSessionId());
cookies.put("s_session_id", getSSessionId());
return cookies;
}
public boolean isOtherUser(String username) {
return !this.getUsername().equals(username);
}
@NonNull
@Override
public String toString() {
StringBuilder result = new StringBuilder();
HashMap<String, String> cookies = this.getCookies();
for (String header: cookies.keySet()) {
result.append(header).append("=").append(cookies.get(header)).append(";");
}
return result.substring(0, result.length()-1);
}
public String toJsonString() {
JSONObject json = new JSONObject();
try {
json.put("s_session_id", s_session_id);
json.put("session_id", session_id);
json.put("username", username);
json.put("id", id);
json.put("studentId", studentId);
json.put("isAvailable", isAvailable);
} catch (JSONException e) {
return null;
}
return json.toString();
}
private static LoginTokenBB fromJsonString(String tokenString) {
try {
JSONObject json = new JSONObject(tokenString);
LoginTokenBB token = new LoginTokenBB(
json.getString("username"),
json.getString("s_session_id"),
json.getString("session_id"));
if (!json.isNull("id"))
token.setAdditionals(
json.getString("id"),
json.getString("studentId")
);
if (!json.optBoolean("isAvailable", true)) {
token.setNotAvailable();
}
return token;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
@Override
public int hashCode() {
return Objects.hashCode(s_session_id, session_id, username, id, studentId);
}
public interface LoginTokenInterface {
void run(LoginTokenBB token);
}
}

View File

@@ -5,13 +5,20 @@ import android.content.Context;
import com.google.android.gms.common.internal.Objects;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
@@ -19,18 +26,20 @@ import java.util.LinkedHashSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.UtilsJson;
import static de.sebse.fuplanner.tools.UtilsJson.collectionToJson;
import static de.sebse.fuplanner.tools.UtilsJson.jsonArrayToIterableObject;
/**
* Created by sebastian on 29.10.17.
*/
public class Modules implements Iterable<Modules.Module>, Serializable {
public static final int TYPE_KVV = 1;
public static final int TYPE_BB = 2;
public class Modules implements Iterable<Modules.Module> {
private SortedListModule list;
private final String mUsername;
private transient long mLastTimestamp = 0;
private long mLoadTime;
//private transient Logger log = new Logger(this);
private static final String FILE_NAME = "ModuleListSaving";
private static final String FILE_NAME_TIMESTAMP = "ModuleListSavingTimestamp";
@@ -39,14 +48,9 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
this.list = new SortedListModule();
}
public Module addModule(@Nullable Semester semester, HashSet<String> lvNumber, String title, LinkedHashSet<Lecturer> lecturer, String type, String description, String ID, int moduleType) {
Module m = new Module(semester, lvNumber, title, lecturer, type, description, ID, moduleType);
public void addModule(@Nullable Semester semester, HashSet<String> lvNumber, String title, LinkedHashSet<Lecturer> lecturer, String type, String description, String ID) {
Module m = new Module(semester, lvNumber, title, lecturer, type, description, ID);
this.list.add(m);
return m;
}
public void addModule(Module module) {
this.list.add(module);
}
@NonNull
@@ -65,10 +69,6 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
return this.list.filteredIterator(this.list.getLatestSemester());
}
public Semester getLatestSemester() {
return this.list.getLatestSemester();
}
public int size() {
return this.list.size();
}
@@ -81,47 +81,54 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
return this.list.get(index);
}
public static Modules load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof Modules))
return null;
Modules modules = (Modules) readObject;
is.close();
fis.close();
public static Modules load(Context context) throws IOException {
String ret = "";
InputStream inputStream = context.openFileInput(FILE_NAME);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
is = new ObjectInputStream(fis);
modules.mLastTimestamp = is.readLong();
is.close();
fis.close();
return modules;
}
public boolean isNewerVersionInStorage(Context context) throws IOException {
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
ObjectInputStream is = new ObjectInputStream(fis);
boolean result = this.mLastTimestamp < is.readLong();
is.close();
fis.close();
return result;
try {
JSONObject json = new JSONObject(ret);
Modules mod = new Modules(json.getString("username"));
JSONArray arr = json.getJSONArray("modules");
for (JSONObject jsonObject: jsonArrayToIterableObject(arr)) {
mod.list.add(new Module(jsonObject));
}
FileInputStream ofi = context.openFileInput(FILE_NAME_TIMESTAMP);
ObjectInputStream inputStream1 = new ObjectInputStream(ofi);
mod.mLoadTime = inputStream1.readLong();
return mod;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public void save(Context context) throws IOException {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
JSONObject json = new JSONObject();
try {
json.put("username", mUsername);
json.put("modules", UtilsJson.collectionToJson(list));
OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE));
osw.write(json.toString());
osw.close();
} catch (JSONException e) {
e.printStackTrace();
}
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
this.mLastTimestamp = System.currentTimeMillis();
os.writeLong(this.mLastTimestamp);
os.close();
fos.close();
mLoadTime = System.currentTimeMillis();
FileOutputStream ofo = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(ofo);
outputStream.writeLong(mLoadTime);
}
public void delete(Context context) {
@@ -150,8 +157,6 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
isChanged = true;
}
}
if (this.list.size() != old.size())
isChanged = true;
return isChanged;
}
@@ -164,23 +169,43 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
return o1.hashCode() == o2.hashCode();
}
public class Module implements Serializable {
public static class Module implements UtilsJson.JsonConvertible {
@Nullable public final Semester semester;
@NotNull public final HashSet<String> lvNumber;
@NotNull final HashSet<String> lvNumber;
@NotNull public final String title;
@NotNull
public ArrayList<Lecturer> lecturer;
@NotNull public final ArrayList<Lecturer> lecturer;
@Nullable public final String type;
@Nullable public final String description;
@NotNull private final String ID;
@NotNull private final int moduleType;
@Nullable public ArrayList<Announcement> announcements;
@Nullable public AssignmentList assignments;
@Nullable public EventList events;
@Nullable public ArrayList<Grade> gradebook;
@Nullable public ArrayList<Resource> resources;
@Override
public int hashCode() {
return Objects.hashCode(semester, lvNumber, title, lecturer, type, description, ID);
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("semester", semester != null ? semester.toJSONObject() : null);
json.put("lvNumber", collectionToJson(lvNumber));
json.put("title", title);
json.put("lecturer", collectionToJson(lecturer));
json.put("type", type);
json.put("description", description);
json.put("ID", ID);
json.put("announcements", collectionToJson(announcements));
json.put("assignments", collectionToJson(assignments));
json.put("events", collectionToJson(events));
json.put("gradebook", collectionToJson(gradebook));
json.put("resources", collectionToJson(resources));
return json;
}
public float getGradebookPercent(){
float maxPoint = 0;
float userPoint = 0;
@@ -195,7 +220,7 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
return userPoint/maxPoint;
}
private Module(@Nullable Semester semester, @NotNull HashSet<String> lvNumber, @NotNull String title, @NotNull LinkedHashSet<Lecturer> lecturer, @Nullable String type, @Nullable String description, @NotNull String ID, @NotNull int moduleType) {
private Module(@Nullable Semester semester, @NotNull HashSet<String> lvNumber, @NotNull String title, @NotNull LinkedHashSet<Lecturer> lecturer, @Nullable String type, @Nullable String description, @NotNull String ID) {
title = title.replaceAll("(.*?) (S[0-9]{2}|W[0-9/]{5})", "$1");
@@ -206,11 +231,71 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
this.type = type;
this.description = description;
this.ID = ID;
this.moduleType = moduleType;
}
public void setLecturers(LinkedHashSet<Lecturer> lecturers) {
this.lecturer = new ArrayList<>(lecturers);
private Module(@NotNull JSONObject json) throws JSONException {
HashSet<String> lv = new HashSet<>();
for (String number: UtilsJson.jsonArrayToIterableString(json.getJSONArray("lvNumber"))) {
lv.add(number);
}
LinkedHashSet<Lecturer> lecturer = new LinkedHashSet<>();
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(json.getJSONArray("lecturer"))) {
lecturer.add(new Lecturer(l));
}
JSONObject obj = json.optJSONObject("semester");
this.semester = obj != null ? new Semester(obj) : null;
this.lvNumber = lv;
this.title = json.getString("title");
this.lecturer = new ArrayList<>(lecturer);
this.type = json.getString("type");
this.description = json.getString("description");
this.ID = json.getString("ID");
JSONArray arr = json.optJSONArray("announcements");
if (obj != null) {
ArrayList<Announcement> announce = new ArrayList<>();
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
announce.add(new Announcement(l));
}
this.announcements = announce;
}
arr = json.optJSONArray("assignments");
if (obj != null) {
AssignmentList assign = new AssignmentList();
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
assign.add(new Assignment(l));
}
this.assignments = assign;
}
arr = json.optJSONArray("events");
if (obj != null) {
EventList events = new EventList();
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
events.add(new Event(l));
}
this.events = events;
}
arr = json.optJSONArray("gradebook");
if (obj != null) {
ArrayList<Grade> grades = new ArrayList<>();
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
grades.add(new Grade(l));
}
this.gradebook = grades;
}
arr = json.optJSONArray("resources");
if (obj != null) {
ArrayList<Resource> res = new ArrayList<>();
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
if (l.getString("restype").equals("file"))
res.add(new Resource.File(l));
else
res.add(new Resource.Folder(l));
}
this.resources = res;
}
}
@NonNull
@@ -228,18 +313,5 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
"\ntype: "+type+
"\nID: "+ID;
}
@Override
public int hashCode() {
return Objects.hashCode(semester, lvNumber, title, lecturer, type, description, ID, moduleType);
}
public int getModuleType() {
return moduleType;
}
public Module clone() {
return new Module(semester, lvNumber, title, new LinkedHashSet<>(lecturer), type, description, ID, moduleType);
}
}
}

View File

@@ -2,17 +2,20 @@ package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.tools.UtilsJson;
import de.sebse.fuplanner.tools.ui.treeview.LayoutItemType;
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
public abstract class Resource implements Serializable {
public abstract class Resource implements UtilsJson.JsonConvertible {
final String author;
final long modifiedDate;
@@ -62,75 +65,17 @@ public abstract class Resource implements Serializable {
return Objects.hashCode(getAuthor(), getContainer(), getModifiedDate(), getTitle(), getUrl());
}
public static class Document extends Resource implements LayoutItemType {
private final ArrayList<DownloadFile> urls;
private final String body;
public Document(String author, String title, long modifiedDate, String url, boolean visible, String container, String body) {
super(author, title, modifiedDate, url, visible, container);
this.body = body;
this.urls = new ArrayList<>();
}
@NonNull
@Override
public String toString() {
return "Resource{" +
"author='" + author + '\'' +
", modifiedDate=" + modifiedDate +
", title='" + title + '\'' +
", url='" + url + '\'' +
", body='" + body + '\'' +
", urls='" + urls + '\'' +
'}';
}
public String getBody() {
return body;
}
public void addUrl(String url, String name){
urls.add(new DownloadFile(url, name));
}
public DownloadFile getUrl(int id){
return urls.get(id);
}
public int size(){
return urls.size();
}
@Override
public TreeNode getTreeNode() {
return new TreeNode<>(this);
}
@Override
public @LayoutRes int getLayoutId() {
return R.layout.list_announcement_items;
}
@Override
public int hashCode() {
return Objects.hashCode(super.hashCode(), urls, body, this.getClass().getSimpleName());
}
public class DownloadFile implements Serializable {
public final String url;
public final String name;
public DownloadFile(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public int hashCode() {
return Objects.hashCode(url, name);
}
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("author", author);
json.put("modifiedDate", modifiedDate);
json.put("title", title);
json.put("url", url);
json.put("visible", visible);
json.put("container", container);
json.put("restype", "");
return json;
}
public static class File extends Resource implements LayoutItemType {
@@ -164,8 +109,11 @@ public abstract class Resource implements Serializable {
}
@Override
public int hashCode() {
return Objects.hashCode(super.hashCode(), this.type, this.getClass().getSimpleName());
public JSONObject toJSONObject() throws JSONException {
JSONObject json = super.toJSONObject();
json.put("type", type);
json.put("restype", "file");
return json;
}
}
@@ -216,8 +164,11 @@ public abstract class Resource implements Serializable {
}
@Override
public int hashCode() {
return Objects.hashCode(super.hashCode(), children, this.getClass().getSimpleName());
public JSONObject toJSONObject() throws JSONException {
JSONObject json = super.toJSONObject();
json.put("children", UtilsJson.collectionToJson(children));
json.put("restype", "dir");
return json;
}
}
}

View File

@@ -1,11 +1,13 @@
package de.sebse.fuplanner.services.kvv.types;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.UtilsJson;
public class Semester implements Serializable {
public class Semester implements UtilsJson.JsonConvertible {
public static final int SEM_WS = 1;
public static final int SEM_SS = 2;
private int type;
@@ -17,25 +19,17 @@ public class Semester implements Serializable {
}
public Semester(String semester_string) throws NoSuchFieldException {
/*Semester sem = null;
if (semester != null) {
sem = new Semester(semester)
semester = semester.replace("SS", "S");
semester = semester.replaceAll("[0-9]{2}([0-9]{2})", "$1");
}*/
/*String s1type = Regex.regex("^(S|WS) ", a);
int s1year = Integer.parseInt(Regex.regex("^(S|WS) ([0-9]{2})", a, 2));
String s2type = Regex.regex("^(S|WS) ", b);
int s2year = Integer.parseInt(Regex.regex("^(S|WS) ([0-9]{2})", b, 2));*/
String type = Regex.regex("^(SS|WS) ", semester_string);
String year = Regex.regex("^(SS|WS) ([0-9]{2})", semester_string, 2);
this.type = type.equals("SS") ? SEM_SS : SEM_WS;
this.year = Integer.parseInt(year);
}
public Semester(JSONObject json) throws JSONException {
this.type = json.getInt("type");
this.year = json.getInt("year");
}
public int getType() {
return type;
}
@@ -52,4 +46,12 @@ public class Semester implements Serializable {
}
return false;
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("type", type);
json.put("year", year);
return json;
}
}

View File

@@ -1,5 +1,8 @@
package de.sebse.fuplanner.services.kvv.types;
import org.json.JSONException;
import org.json.JSONObject;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.SortedList;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,12 +3,11 @@ package de.sebse.fuplanner.tools;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public abstract class SortedList<T, I, F> implements Iterable<T>, Serializable {
public abstract class SortedList<T, I, F> implements Iterable<T> {
private final ArrayList<T> internalList = new ArrayList<>();

View File

@@ -0,0 +1,109 @@
package de.sebse.fuplanner.tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class UtilsJson {
public static JSONArray collectionToJson(@Nullable HashSet<String> coll) {
if (coll == null)
return null;
JSONArray arr = new JSONArray();
for (String e: coll) {
arr.put(e);
}
return arr;
}
public static <E extends JsonConvertible> JSONArray collectionToJson(@Nullable Collection<E> coll) throws JSONException {
if (coll == null)
return null;
JSONArray arr = new JSONArray();
for (E e: coll) {
arr.put(e.toJSONObject());
}
return arr;
}
public static JSONArray collectionToJson(@Nullable ArrayList<String> coll) throws JSONException {
if (coll == null)
return null;
JSONArray arr = new JSONArray();
for (String e: coll) {
arr.put(e);
}
return arr;
}
public static <A extends JsonConvertible> JSONArray collectionToJson(@Nullable SortedList<A, ?, ?> coll) throws JSONException {
if (coll == null)
return null;
JSONArray arr = new JSONArray();
for (A e: coll) {
arr.put(e.toJSONObject());
}
return arr;
}
public static <T> Iterator<T> jsonArrayToIterator(JSONArray array, GetInterface<T> func) {
return new Iterator<T>() {
int size = array == null ? 0 : array.length();
int pos = 0;
@Override
public boolean hasNext() {
return pos < size;
}
@Override
public T next() {
try {
return func.get(array, pos++);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
};
}
@FunctionalInterface
private interface GetInterface<T> {
T get(JSONArray array, int index) throws JSONException;
}
public static JsonIterable<JSONObject> jsonArrayToIterableObject(JSONArray array) {
return new JsonIterable<>(array, JSONArray::getJSONObject);
}
public static JsonIterable<String> jsonArrayToIterableString(JSONArray array) {
return new JsonIterable<>(array, JSONArray::getString);
}
public static class JsonIterable<T> implements Iterable<T> {
private JSONArray array;
private GetInterface<T> getInterface;
JsonIterable(JSONArray array, GetInterface<T> getInterface) {
this.array = array;
this.getInterface = getInterface;
}
@NonNull
@Override
public Iterator<T> iterator() {
return UtilsJson.jsonArrayToIterator(array, getInterface);
}
}
public interface JsonConvertible {
JSONObject toJSONObject() throws JSONException;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 427 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 320 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 472 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 879 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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