[Config] Add the rest of config. Migrate from AppConfig and remove most values from AppConfig.

This commit is contained in:
Kuba Szczodrzyński 2019-12-01 22:35:42 +01:00
parent acf364166b
commit 7b04202a00
42 changed files with 742 additions and 455 deletions

View File

@ -18,7 +18,6 @@ import android.os.Handler;
import android.provider.Settings;
import android.util.Base64;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatDelegate;
@ -71,7 +70,6 @@ import okhttp3.TlsVersion;
import pl.szczodrzynski.edziennik.config.Config;
import pl.szczodrzynski.edziennik.data.db.AppDb;
import pl.szczodrzynski.edziennik.data.db.modules.debuglog.DebugLog;
import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore;
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile;
import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull;
import pl.szczodrzynski.edziennik.network.NetworkUtils;
@ -84,9 +82,7 @@ import pl.szczodrzynski.edziennik.utils.Themes;
import pl.szczodrzynski.edziennik.utils.Utils;
import pl.szczodrzynski.edziennik.utils.models.AppConfig;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_LIBRUS;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_MOBIDZIENNIK;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_VULCAN;
public class App extends androidx.multidex.MultiDexApplication implements Configuration.Provider {
private static final String TAG = "App";
@ -197,6 +193,7 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
networkUtils = new NetworkUtils(this);
config = new Config(db);
config.migrate(this);
Iconics.init(getApplicationContext());
Iconics.registerFont(SzkolnyFont.INSTANCE);
@ -212,7 +209,7 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
loadConfig();
Themes.INSTANCE.setThemeInt(appConfig.appTheme);
Themes.INSTANCE.setThemeInt(config.getUi().getTheme());
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
@ -231,7 +228,7 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
if ("f054761fbdb6a238".equals(deviceId) || BuildConfig.DEBUG) {
devMode = true;
}
else if (appConfig.devModePassword != null) {
else if (config.getDevModePassword() != null) {
checkDevModePassword();
}
@ -302,7 +299,7 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
//profileLoadById(appSharedPrefs.getInt("current_profile_id", 1));
if (appConfig.registerSyncEnabled) {
if (config.getSync().getEnabled()) {
SyncWorker.Companion.scheduleNext(this, false);
}
else {
@ -366,11 +363,10 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
shortcutManager.setDynamicShortcuts(Arrays.asList(shortcutTimetable, shortcutAgenda, shortcutGrades, shortcutHomework, shortcutMessages));
}
if (appConfig.appInstalledTime == 0) {
if (config.getAppInstalledTime() == 0) {
try {
appConfig.appInstalledTime = getPackageManager().getPackageInfo(getPackageName(), 0).firstInstallTime;
appConfig.appRateSnackbarTime = appConfig.appInstalledTime + 7 * 24 * 60 * 60 * 1000;
saveConfig("appInstalledTime", "appRateSnackbarTime");
config.setAppInstalledTime(getPackageManager().getPackageInfo(getPackageName(), 0).firstInstallTime);
config.setAppRateSnackbarTime(config.getAppInstalledTime() + 7 * 24 * 60 * 60 * 1000);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
@ -438,9 +434,9 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
final long startTime = System.currentTimeMillis();
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> {
Log.d(TAG, "Token for App is " + instanceIdResult.getToken() + ", ID is " + instanceIdResult.getId()+". Time is "+(System.currentTimeMillis() - startTime));
appConfig.fcmToken = instanceIdResult.getToken();
config.getSync().setTokenApp(instanceIdResult.getToken());
});
FirebaseInstanceId.getInstance(pushMobidziennikApp).getInstanceId().addOnSuccessListener(instanceIdResult -> {
/*FirebaseInstanceId.getInstance(pushMobidziennikApp).getInstanceId().addOnSuccessListener(instanceIdResult -> {
Log.d(TAG, "Token for Mobidziennik is " + instanceIdResult.getToken() + ", ID is " + instanceIdResult.getId());
appConfig.fcmTokens.put(LOGIN_TYPE_MOBIDZIENNIK, new Pair<>(instanceIdResult.getToken(), new ArrayList<>()));
});
@ -454,7 +450,7 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
if (pair == null || pair.first == null || !pair.first.equals(instanceIdResult.getToken())) {
appConfig.fcmTokens.put(LOGIN_TYPE_VULCAN, new Pair<>(instanceIdResult.getToken(), new ArrayList<>()));
}
});
});*/
FirebaseMessaging.getInstance().subscribeToTopic(getPackageName());
@ -517,7 +513,8 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
appSharedPrefs.edit().remove("app.appConfig."+fieldName).apply();
Log.w(TAG, "Should remove app.appConfig."+fieldName);
//appSharedPrefs.edit().remove("app.appConfig."+fieldName).apply(); TODO migration
}
}
}
@ -589,7 +586,11 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
//appSharedPrefs.edit().putString("config", gson.toJson(appConfig)).apply();
}
public void profileSave() {
AsyncTask.execute(() -> {
db.profileDao().add(profile);
});
}
public void profileSaveAsync() {
AsyncTask.execute(() -> {
@ -610,14 +611,6 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
db.profileDao().add(profileFull);
db.loginStoreDao().add(profileFull);
}
public void profileSaveFull(Profile profile, LoginStore loginStore) {
db.profileDao().add(profile);
db.loginStoreDao().add(loginStore);
}
public ProfileFull profileGetOrNull(int id) {
return db.profileDao().getFullByIdNow(id);
}
public void profileLoadById(int id) {
profileLoadById(id, false);
@ -711,7 +704,7 @@ public class App extends androidx.multidex.MultiDexApplication implements Config
public void checkDevModePassword() {
try {
devMode = Utils.AESCrypt.decrypt("nWFVxY65Pa8/aRrT7EylNAencmOD+IxUY2Gg/beiIWY=", appConfig.devModePassword).equals("ok here you go it's enabled now")
devMode = Utils.AESCrypt.decrypt("nWFVxY65Pa8/aRrT7EylNAencmOD+IxUY2Gg/beiIWY=", config.getDevModePassword()).equals("ok here you go it's enabled now")
|| BuildConfig.DEBUG;
} catch (Exception e) {
e.printStackTrace();

View File

@ -0,0 +1,319 @@
/*
* Copyright (c) Kuba Szczodrzyński 2019-11-26.
*/
package pl.szczodrzynski.edziennik
import android.util.Log
import androidx.work.Configuration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
class Szkolny : /*MultiDexApplication(),*/ Configuration.Provider, CoroutineScope {
companion object {
var devMode = false
}
//lateinit var db: AppDb
//val config by lazy { Config(db); // TODO migrate }
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun getWorkManagerConfiguration() = Configuration.Builder()
.setMinimumLoggingLevel(Log.VERBOSE)
.build()
/*val preferences by lazy { getSharedPreferences(getString(R.string.preference_file), Context.MODE_PRIVATE) }
val notifier by lazy { Notifier(this) }
val permissionChecker by lazy { PermissionChecker(this) }
lateinit var profile: ProfileFull
/* _ _ _______ _______ _____
| | | |__ __|__ __| __ \
| |__| | | | | | | |__) |
| __ | | | | | | ___/
| | | | | | | | | |
|_| |_| |_| |_| |*/
val http: OkHttpClient by lazy {
val builder = OkHttpClient.Builder()
.cache(null)
.followRedirects(true)
.followSslRedirects(true)
.retryOnConnectionFailure(true)
.cookieJar(cookieJar)
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
builder.installHttpsSupport()
if (devMode || BuildConfig.DEBUG) {
HyperLog.initialize(this)
HyperLog.setLogLevel(Log.VERBOSE)
HyperLog.setLogFormat(DebugLogFormat(this))
val chuckerCollector = ChuckerCollector(this, true, Period.ONE_HOUR)
val chuckerInterceptor = ChuckerInterceptor(this, chuckerCollector)
builder.addInterceptor(chuckerInterceptor)
}
builder.build()
}
val httpLazy: OkHttpClient by lazy {
http.newBuilder()
.followRedirects(false)
.followSslRedirects(false)
.build()
}
val cookieJar by lazy { PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(this)) }
/* _____ _ _
/ ____(_) | |
| (___ _ __ _ _ __ __ _| |_ _ _ _ __ ___
\___ \| |/ _` | '_ \ / _` | __| | | | '__/ _ \
____) | | (_| | | | | (_| | |_| |_| | | | __/
|_____/|_|\__, |_| |_|\__,_|\__|\__,_|_| \___|
__/ |
|__*/
private val deviceId: String by lazy { Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) ?: "" }
private val signature: String by lazy {
var str = ""
try {
val packageInfo: PackageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
for (signature in packageInfo.signatures) {
val signatureBytes = signature.toByteArray()
val md = MessageDigest.getInstance("SHA")
md.update(signatureBytes)
str = Base64.encodeToString(md.digest(), Base64.DEFAULT)
}
} catch (e: Exception) {
e.printStackTrace()
}
str
}
private var unreadBadgesAvailable = true
/* _____ _
/ ____| | |
___ _ __ | | _ __ ___ __ _| |_ ___
/ _ \| '_ \| | | '__/ _ \/ _` | __/ _ \
| (_) | | | | |____| | | __/ (_| | || __/
\___/|_| |_|\_____|_| \___|\__,_|\__\__*/
override fun onCreate() {
super.onCreate()
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
CaocConfig.Builder.create()
.backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM)
.enabled(true)
.showErrorDetails(true)
.showRestartButton(true)
.logErrorOnRestart(true)
.trackActivities(true)
.minTimeBetweenCrashesMs(60*1000)
.errorDrawable(R.drawable.ic_rip)
.restartActivity(MainActivity::class.java)
.errorActivity(CrashActivity::class.java)
.apply()
Iconics.init(applicationContext)
Iconics.registerFont(SzkolnyFont)
db = AppDb.getDatabase(this)
Themes.themeInt = config.ui.theme
MHttp.instance().customOkHttpClient(http)
devMode = "f054761fbdb6a238" == deviceId || BuildConfig.DEBUG
if (config.devModePassword != null)
checkDevModePassword()
launch { async(Dispatchers.Default) {
if (config.sync.enabled) {
scheduleNext(this@App, false)
} else {
cancelNext(this@App)
}
db.metadataDao().countUnseen().observeForever { count: Int ->
if (unreadBadgesAvailable)
unreadBadgesAvailable = ShortcutBadger.applyCount(this@App, count)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
val shortcutManager = getSystemService(ShortcutManager::class.java)
val shortcutTimetable = ShortcutInfo.Builder(this@App, "item_timetable")
.setShortLabel(getString(R.string.shortcut_timetable)).setLongLabel(getString(R.string.shortcut_timetable))
.setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_timetable))
.setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java)
.putExtra("fragmentId", MainActivity.DRAWER_ITEM_TIMETABLE))
.build()
val shortcutAgenda = ShortcutInfo.Builder(this@App, "item_agenda")
.setShortLabel(getString(R.string.shortcut_agenda)).setLongLabel(getString(R.string.shortcut_agenda))
.setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_agenda))
.setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java)
.putExtra("fragmentId", MainActivity.DRAWER_ITEM_AGENDA))
.build()
val shortcutGrades = ShortcutInfo.Builder(this@App, "item_grades")
.setShortLabel(getString(R.string.shortcut_grades)).setLongLabel(getString(R.string.shortcut_grades))
.setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_grades))
.setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java)
.putExtra("fragmentId", MainActivity.DRAWER_ITEM_GRADES))
.build()
val shortcutHomework = ShortcutInfo.Builder(this@App, "item_homeworks")
.setShortLabel(getString(R.string.shortcut_homework)).setLongLabel(getString(R.string.shortcut_homework))
.setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_homework))
.setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java)
.putExtra("fragmentId", MainActivity.DRAWER_ITEM_HOMEWORK))
.build()
val shortcutMessages = ShortcutInfo.Builder(this@App, "item_messages")
.setShortLabel(getString(R.string.shortcut_messages)).setLongLabel(getString(R.string.shortcut_messages))
.setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_messages))
.setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java)
.putExtra("fragmentId", MainActivity.DRAWER_ITEM_MESSAGES))
.build()
shortcutManager.dynamicShortcuts = listOf(
shortcutTimetable,
shortcutAgenda,
shortcutGrades,
shortcutHomework,
shortcutMessages
)
} // shortcuts - end
if (config.appInstalledTime == 0L)
try {
config.appInstalledTime = packageManager.getPackageInfo(packageName, 0).firstInstallTime
config.appRateSnackbarTime = config.appInstalledTime + 7*DAY*MS
} catch (e: NameNotFoundException) {
e.printStackTrace()
}
val pushMobidziennikApp = FirebaseApp.initializeApp(
this@App,
FirebaseOptions.Builder()
.setApiKey("AIzaSyCi5LmsZ5BBCQnGtrdvWnp1bWLCNP8OWQE")
.setApplicationId("1:747285019373:android:f6341bf7b158621d")
.build(),
"Mobidziennik2"
)
val pushLibrusApp = FirebaseApp.initializeApp(
this@App,
FirebaseOptions.Builder()
.setApiKey("AIzaSyDfTuEoYPKdv4aceEws1CO3n0-HvTndz-o")
.setApplicationId("1:513056078587:android:1e29083b760af544")
.build(),
"Librus"
)
val pushVulcanApp = FirebaseApp.initializeApp(
this@App,
FirebaseOptions.Builder()
.setApiKey("AIzaSyDW8MUtanHy64_I0oCpY6cOxB3jrvJd_iA")
.setApplicationId("1:987828170337:android:ac97431a0a4578c3")
.build(),
"Vulcan"
)
try {
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { instanceIdResult ->
val token = instanceIdResult.token
config.sync.tokenApp = token
}
FirebaseInstanceId.getInstance(pushMobidziennikApp).instanceId.addOnSuccessListener { instanceIdResult ->
val token = instanceIdResult.token
if (token != config.sync.tokenMobidziennik) {
config.sync.tokenMobidziennik = token
config.sync.tokenMobidziennikList = listOf()
}
}
FirebaseInstanceId.getInstance(pushLibrusApp).instanceId.addOnSuccessListener { instanceIdResult ->
val token = instanceIdResult.token
if (token != config.sync.tokenLibrus) {
config.sync.tokenLibrus = token
config.sync.tokenLibrusList = listOf()
}
}
FirebaseInstanceId.getInstance(pushVulcanApp).instanceId.addOnSuccessListener { instanceIdResult ->
val token = instanceIdResult.token
if (token != config.sync.tokenVulcan) {
config.sync.tokenVulcan = token
config.sync.tokenVulcanList = listOf()
}
}
FirebaseMessaging.getInstance().subscribeToTopic(packageName)
} catch (e: IllegalStateException) {
e.printStackTrace()
}
}}
}
private fun profileLoad(profileId: Int) {
db.profileDao().getFullByIdNow(profileId)?.also {
profile = it
} ?: run {
if (!::profile.isInitialized) {
profile = ProfileFull(-1, "", "", -1)
}
}
}
fun profileLoad(profileId: Int, onSuccess: (profile: ProfileFull) -> Unit) {
launch {
val deferred = async(Dispatchers.Default) {
profileLoad(profileId)
}
deferred.await()
onSuccess(profile)
}
}
private fun OkHttpClient.Builder.installHttpsSupport() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
try {
try {
ProviderInstaller.installIfNeeded(this@App)
} catch (e: Exception) {
Log.e("OkHttpTLSCompat", "Play Services not found or outdated")
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val x509TrustManager = trustManagerFactory.trustManagers.singleOrNull { it is X509TrustManager } as X509TrustManager?
?: return
val sc = SSLContext.getInstance("TLSv1.2")
sc.init(null, null, null)
sslSocketFactory(TLSSocketFactory(sc.socketFactory), x509TrustManager)
val cs: ConnectionSpec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_0)
.tlsVersions(TlsVersion.TLS_1_1)
.tlsVersions(TlsVersion.TLS_1_2)
.build()
val specs: MutableList<ConnectionSpec> = ArrayList()
specs.add(cs)
specs.add(ConnectionSpec.COMPATIBLE_TLS)
specs.add(ConnectionSpec.CLEARTEXT)
connectionSpecs(specs)
}
} catch (exc: Exception) {
Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc)
}
}
}
fun checkDevModePassword() {
devMode = try {
Utils.AESCrypt.decrypt("nWFVxY65Pa8/aRrT7EylNAencmOD+IxUY2Gg/beiIWY=", config.devModePassword) == "ok here you go it's enabled now" || BuildConfig.DEBUG
} catch (e: Exception) {
e.printStackTrace()
false
}
}*/
}

View File

@ -200,6 +200,7 @@ const val DAY = 24L*HOUR
const val WEEK = 7L*DAY
const val MONTH = 30L*DAY
const val YEAR = 365L*DAY
const val MS = 1000L
fun <T> LongSparseArray<T>.values(): List<T> {
val result = mutableListOf<T>()

View File

@ -243,7 +243,7 @@ class MainActivity : AppCompatActivity() {
setTheme(Themes.appTheme)
app.appConfig.language?.let {
app.config.ui.language?.let {
setLanguage(it)
}
@ -306,10 +306,10 @@ class MainActivity : AppCompatActivity() {
}
drawer.apply {
setAccountHeaderBackground(app.appConfig.headerBackground)
setAccountHeaderBackground(app.config.ui.headerBackground)
drawerProfileListEmptyListener = {
app.appConfig.loginFinished = false
app.config.loginFinished = false
app.saveConfig("loginFinished")
profileListEmptyListener()
}
@ -334,7 +334,7 @@ class MainActivity : AppCompatActivity() {
drawerProfileSettingClickListener = this@MainActivity.profileSettingClickListener
miniDrawerVisibleLandscape = null
miniDrawerVisiblePortrait = app.appConfig.miniDrawerVisible
miniDrawerVisiblePortrait = app.config.ui.miniMenuVisible
}
}
@ -387,21 +387,23 @@ class MainActivity : AppCompatActivity() {
SyncWorker.scheduleNext(app)
// APP BACKGROUND
if (app.appConfig.appBackground != null) {
if (app.config.ui.appBackground != null) {
try {
var bg = app.appConfig.appBackground
val bgDir = File(Environment.getExternalStoragePublicDirectory("Szkolny.eu"), "bg")
if (bgDir.exists()) {
val files = bgDir.listFiles()
val r = Random()
val i = r.nextInt(files.size)
bg = files[i].toString()
}
val linearLayout = b.root
if (bg.endsWith(".gif")) {
linearLayout.background = GifDrawable(bg)
} else {
linearLayout.background = BitmapDrawable.createFromPath(bg)
app.config.ui.appBackground?.let {
var bg = it
val bgDir = File(Environment.getExternalStoragePublicDirectory("Szkolny.eu"), "bg")
if (bgDir.exists()) {
val files = bgDir.listFiles()
val r = Random()
val i = r.nextInt(files.size)
bg = files[i].toString()
}
val linearLayout = b.root
if (bg.endsWith(".gif")) {
linearLayout.background = GifDrawable(bg)
} else {
linearLayout.background = BitmapDrawable.createFromPath(bg)
}
}
} catch (e: IOException) {
e.printStackTrace()
@ -409,7 +411,7 @@ class MainActivity : AppCompatActivity() {
}
// WHAT'S NEW DIALOG
if (app.appConfig.lastAppVersion != BuildConfig.VERSION_CODE) {
if (app.config.appVersion < BuildConfig.VERSION_CODE) {
ServerRequest(app, app.requestScheme + APP_URL + "main.php?just_updated", "MainActivity/JU")
.run { e, result ->
Handler(Looper.getMainLooper()).post {
@ -420,17 +422,16 @@ class MainActivity : AppCompatActivity() {
}
}
}
if (app.appConfig.lastAppVersion < 170) {
if (app.config.appVersion < 170) {
//Intent intent = new Intent(this, ChangelogIntroActivity.class);
//startActivity(intent);
} else {
app.appConfig.lastAppVersion = BuildConfig.VERSION_CODE
app.saveConfig("lastAppVersion")
app.config.appVersion = BuildConfig.VERSION_CODE
}
}
// RATE SNACKBAR
if (app.appConfig.appRateSnackbarTime != 0L && app.appConfig.appRateSnackbarTime <= System.currentTimeMillis()) {
if (app.config.appRateSnackbarTime != 0L && app.config.appRateSnackbarTime <= System.currentTimeMillis()) {
navView.coordinator.postDelayed({
CafeBar.builder(this)
.content(R.string.rate_snackbar_text)
@ -444,20 +445,17 @@ class MainActivity : AppCompatActivity() {
.onPositive { cafeBar ->
Utils.openGooglePlay(this)
cafeBar.dismiss()
app.appConfig.appRateSnackbarTime = 0
app.saveConfig("appRateSnackbarTime")
app.config.appRateSnackbarTime = 0
}
.onNegative { cafeBar ->
Toast.makeText(this, "Szkoda, opinie innych pomagają mi rozwijać aplikację.", Toast.LENGTH_LONG).show()
cafeBar.dismiss()
app.appConfig.appRateSnackbarTime = 0
app.saveConfig("appRateSnackbarTime")
app.config.appRateSnackbarTime = 0
}
.onNeutral { cafeBar ->
Toast.makeText(this, "OK", Toast.LENGTH_LONG).show()
cafeBar.dismiss()
app.appConfig.appRateSnackbarTime = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000
app.saveConfig("appRateSnackbarTime")
app.config.appRateSnackbarTime = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000
}
.autoDismiss(false)
.swipeToDismiss(true)
@ -696,7 +694,7 @@ class MainActivity : AppCompatActivity() {
}
when {
app.profile == null -> {
app.profile == null || app.profile.id == -1 -> {
if (intentProfileId == -1)
intentProfileId = app.appSharedPrefs.getInt("current_profile_id", 1)
loadProfile(intentProfileId, intentTargetId, extras)
@ -763,7 +761,7 @@ class MainActivity : AppCompatActivity() {
finish()
}
else {
if (!app.appConfig.loginFinished)
if (!app.config.loginFinished)
finish()
else {
handleIntent(data?.extras)
@ -800,7 +798,7 @@ class MainActivity : AppCompatActivity() {
this.runOnUiThread {
if (app.profile == null) {
LoginActivity.firstCompleted = false
if (app.appConfig.loginFinished) {
if (app.config.loginFinished) {
// this shouldn't run
profileListEmptyListener()
}

View File

@ -93,8 +93,8 @@ public class Notifier {
public boolean shouldBeQuiet() {
long now = Time.getNow().getInMillis();
long start = app.appConfig.quietHoursStart;
long end = app.appConfig.quietHoursEnd;
long start = app.config.getSync().getQuietHoursStart();
long end = app.config.getSync().getQuietHoursEnd();
if (start > end) {
end += 1000 * 60 * 60 * 24;
//Log.d(TAG, "Night passing");
@ -104,7 +104,7 @@ public class Notifier {
//Log.d(TAG, "Now is smaller");
}
//Log.d(TAG, "Start is "+start+", now is "+now+", end is "+end);
return app.appConfig.quietHoursStart > 0 && now >= start && now <= end;
return start > 0 && now >= start && now <= end;
}
public int getNotificationDefaults() {
@ -312,7 +312,7 @@ public class Notifier {
| |
|*/
public void notificationUpdatesShow(String updateVersion, String updateUrl, String updateFilename, boolean updateDirect) {
if (!app.appConfig.notifyAboutUpdates)
if (!app.config.getSync().getNotifyAboutUpdates())
return;
Intent notificationIntent = new Intent(app.getContext(), BootReceiver.NotificationActionService.class)
.putExtra("update_version", updateVersion)
@ -340,7 +340,7 @@ public class Notifier {
}
public void notificationUpdatesHide() {
if (!app.appConfig.notifyAboutUpdates)
if (!app.config.getSync().getNotifyAboutUpdates())
return;
notificationManager.cancel(ID_UPDATES);
}

View File

@ -1,44 +0,0 @@
/*
* Copyright (c) Kuba Szczodrzyński 2019-11-26.
*/
package pl.szczodrzynski.edziennik
import android.util.Log
import androidx.work.Configuration
class Szkolny : /*MultiDexApplication(),*/ Configuration.Provider {
/*val db by lazy { AppDb.getDatabase(this) }
val networkUtils by lazy { NetworkUtils(this) }
val notifier by lazy { Notifier(this) }
val permissionChecker by lazy { PermissionChecker(this) }
val cookieJar by lazy { PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(this)) }
val deviceId: String by lazy { Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) ?: "" }*/
override fun getWorkManagerConfiguration() = Configuration.Builder()
.setMinimumLoggingLevel(Log.VERBOSE)
.build()
/*override fun onCreate() {
super.onCreate()
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
CaocConfig.Builder.create()
.backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM)
.enabled(true)
.showErrorDetails(true)
.showRestartButton(true)
.logErrorOnRestart(true)
.trackActivities(true)
.minTimeBetweenCrashesMs(60*1000)
.errorDrawable(R.drawable.ic_rip)
.restartActivity(MainActivity::class.java)
.errorActivity(CrashActivity::class.java)
//.eventListener(new YourCustomEventListener())
.apply()
Iconics.init(applicationContext)
Iconics.registerFont(SzkolnyFont)
}*/
}

View File

@ -60,7 +60,7 @@ val LibrusFeatures = listOf(
Feature(LOGIN_TYPE_LIBRUS, FEATURE_PUSH_CONFIG, listOf(
ENDPOINT_LIBRUS_API_PUSH_CONFIG to LOGIN_METHOD_LIBRUS_API
), listOf(LOGIN_METHOD_LIBRUS_API)).withShouldSync { data ->
data.app.appConfig.fcmTokens[LOGIN_TYPE_LIBRUS]?.second?.contains(data.profileId) == false
!data.app.config.sync.tokenLibrusList.contains(data.profileId)
},

View File

@ -91,7 +91,7 @@ class MobidziennikLoginWeb(val data: DataMobidziennik, val onSuccess: () -> Unit
.addParameter("ip", data.app.deviceId)
.addParameter("login", data.loginUsername)
.addParameter("haslo", data.loginPassword)
.addParameter("token", data.app.appConfig.fcmTokens[LOGIN_TYPE_MOBIDZIENNIK]?.first)
.addParameter("token", data.app.config.sync.tokenMobidziennik)
.post()
.callback(callback)
.build()

View File

@ -8,6 +8,8 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import pl.szczodrzynski.edziennik.App
import pl.szczodrzynski.edziennik.BuildConfig
import pl.szczodrzynski.edziennik.config.db.ConfigEntry
import pl.szczodrzynski.edziennik.config.utils.ConfigMigration
import pl.szczodrzynski.edziennik.config.utils.get
@ -18,7 +20,7 @@ import kotlin.coroutines.CoroutineContext
class Config(val db: AppDb) : CoroutineScope, AbstractConfig {
companion object {
const val DATA_VERSION = 1
const val DATA_VERSION = 2
}
private val job = Job()
@ -37,12 +39,39 @@ class Config(val db: AppDb) : CoroutineScope, AbstractConfig {
get() { mDataVersion = mDataVersion ?: values.get("dataVersion", 0); return mDataVersion ?: 0 }
set(value) { set("dataVersion", value); mDataVersion = value }
private var mAppVersion: Int? = null
var appVersion: Int
get() { mAppVersion = mAppVersion ?: values.get("appVersion", BuildConfig.VERSION_CODE); return mAppVersion ?: BuildConfig.VERSION_CODE }
set(value) { set("appVersion", value); mAppVersion = value }
private var mLoginFinished: Boolean? = null
var loginFinished: Boolean
get() { mLoginFinished = mLoginFinished ?: values.get("loginFinished", false); return mLoginFinished ?: false }
set(value) { set("loginFinished", value); mLoginFinished = value }
private var mDevModePassword: String? = null
var devModePassword: String?
get() { mDevModePassword = mDevModePassword ?: values.get("devModePassword", null as String?); return mDevModePassword }
set(value) { set("devModePassword", value); mDevModePassword = value }
private var mAppInstalledTime: Long? = null
var appInstalledTime: Long
get() { mAppInstalledTime = mAppInstalledTime ?: values.get("appInstalledTime", 0L); return mAppInstalledTime ?: 0L }
set(value) { set("appInstalledTime", value); mAppInstalledTime = value }
private var mAppRateSnackbarTime: Long? = null
var appRateSnackbarTime: Long
get() { mAppRateSnackbarTime = mAppRateSnackbarTime ?: values.get("appRateSnackbarTime", 0L); return mAppRateSnackbarTime ?: 0L }
set(value) { set("appRateSnackbarTime", value); mAppRateSnackbarTime = value }
private var rawEntries: List<ConfigEntry> = db.configDao().getAllNow()
private val profileConfigs: HashMap<Int, ProfileConfig> = hashMapOf()
init {
rawEntries.toHashMap(-1, values)
}
fun migrate(app: App) {
if (dataVersion < DATA_VERSION)
ConfigMigration(this)
ConfigMigration(app, this)
}
fun getFor(profileId: Int): ProfileConfig {
return profileConfigs[profileId] ?: ProfileConfig(db, profileId, rawEntries)

View File

@ -4,6 +4,19 @@
package pl.szczodrzynski.edziennik.config
class ConfigGrades(val config: Config) {
import pl.szczodrzynski.edziennik.config.utils.get
import pl.szczodrzynski.edziennik.config.utils.set
class ConfigGrades(private val config: Config) {
companion object {
const val ORDER_BY_DATE_DESC = 0
const val ORDER_BY_SUBJECT_ASC = 1
const val ORDER_BY_DATE_ASC = 2
const val ORDER_BY_SUBJECT_DESC = 3
}
private var mOrderBy: Int? = null
var orderBy: Int
get() { mOrderBy = mOrderBy ?: config.values.get("gradesOrderBy", 0); return mOrderBy ?: 0 }
set(value) { config.set("gradesOrderBy", value); mOrderBy = value }
}

View File

@ -7,7 +7,7 @@ package pl.szczodrzynski.edziennik.config
import pl.szczodrzynski.edziennik.config.utils.get
import pl.szczodrzynski.edziennik.config.utils.set
class ConfigSync(val config: Config) {
class ConfigSync(private val config: Config) {
private var mSyncEnabled: Boolean? = null
var enabled: Boolean
get() { mSyncEnabled = mSyncEnabled ?: config.values.get("syncEnabled", true); return mSyncEnabled ?: true }
@ -27,4 +27,61 @@ class ConfigSync(val config: Config) {
var notifyAboutUpdates: Boolean
get() { mNotifyAboutUpdates = mNotifyAboutUpdates ?: config.values.get("notifyAboutUpdates", true); return mNotifyAboutUpdates ?: true }
set(value) { config.set("notifyAboutUpdates", value); mNotifyAboutUpdates = value }
/* ____ _ _ _
/ __ \ (_) | | | |
| | | |_ _ _ ___| |_ | |__ ___ _ _ _ __ ___
| | | | | | | |/ _ \ __| | '_ \ / _ \| | | | '__/ __|
| |__| | |_| | | __/ |_ | | | | (_) | |_| | | \__ \
\___\_\\__,_|_|\___|\__| |_| |_|\___/ \__,_|_| |__*/
private var mQuietHoursStart: Long? = null
var quietHoursStart: Long
get() { mQuietHoursStart = mQuietHoursStart ?: config.values.get("quietHoursStart", 0L); return mQuietHoursStart ?: 0L }
set(value) { config.set("quietHoursStart", value); mQuietHoursStart = value }
private var mQuietHoursEnd: Long? = null
var quietHoursEnd: Long
get() { mQuietHoursEnd = mQuietHoursEnd ?: config.values.get("quietHoursEnd", 0L); return mQuietHoursEnd ?: 0L }
set(value) { config.set("quietHoursEnd", value); mQuietHoursEnd = value }
private var mQuietDuringLessons: Boolean? = null
var quietDuringLessons: Boolean
get() { mQuietDuringLessons = mQuietDuringLessons ?: config.values.get("quietDuringLessons", false); return mQuietDuringLessons ?: false }
set(value) { config.set("quietDuringLessons", value); mQuietDuringLessons = value }
/* ______ _____ __ __ _______ _
| ____/ ____| \/ | |__ __| | |
| |__ | | | \ / | | | ___ | | _____ _ __ ___
| __|| | | |\/| | | |/ _ \| |/ / _ \ '_ \/ __|
| | | |____| | | | | | (_) | < __/ | | \__ \
|_| \_____|_| |_| |_|\___/|_|\_\___|_| |_|__*/
private var mTokenApp: String? = null
var tokenApp: String?
get() { mTokenApp = mTokenApp ?: config.values.get("tokenApp", null as String?); return mTokenApp }
set(value) { config.set("tokenApp", value); mTokenApp = value }
private var mTokenMobidziennik: String? = null
var tokenMobidziennik: String?
get() { mTokenMobidziennik = mTokenMobidziennik ?: config.values.get("tokenMobidziennik", null as String?); return mTokenMobidziennik }
set(value) { config.set("tokenMobidziennik", value); mTokenMobidziennik = value }
private var mTokenLibrus: String? = null
var tokenLibrus: String?
get() { mTokenLibrus = mTokenLibrus ?: config.values.get("tokenLibrus", null as String?); return mTokenLibrus }
set(value) { config.set("tokenLibrus", value); mTokenLibrus = value }
private var mTokenVulcan: String? = null
var tokenVulcan: String?
get() { mTokenVulcan = mTokenVulcan ?: config.values.get("tokenVulcan", null as String?); return mTokenVulcan }
set(value) { config.set("tokenVulcan", value); mTokenVulcan = value }
private var mTokenMobidziennikList: List<Int>? = null
var tokenMobidziennikList: List<Int>
get() { mTokenMobidziennikList = mTokenMobidziennikList ?: config.values.get("tokenMobidziennikList", listOf()); return mTokenMobidziennikList ?: listOf() }
set(value) { config.set("tokenMobidziennikList", value); mTokenMobidziennikList = value }
private var mTokenLibrusList: List<Int>? = null
var tokenLibrusList: List<Int>
get() { mTokenLibrusList = mTokenLibrusList ?: config.values.get("tokenLibrusList", listOf()); return mTokenLibrusList ?: listOf() }
set(value) { config.set("tokenLibrusList", value); mTokenLibrusList = value }
private var mTokenVulcanList: List<Int>? = null
var tokenVulcanList: List<Int>
get() { mTokenVulcanList = mTokenVulcanList ?: config.values.get("tokenVulcanList", listOf()); return mTokenVulcanList ?: listOf() }
set(value) { config.set("tokenVulcanList", value); mTokenVulcanList = value }
}

View File

@ -8,7 +8,7 @@ import pl.szczodrzynski.edziennik.config.utils.get
import pl.szczodrzynski.edziennik.config.utils.set
import pl.szczodrzynski.edziennik.utils.models.Time
class ConfigTimetable(val config: Config) {
class ConfigTimetable(private val config: Config) {
private var mBellSyncMultiplier: Int? = null
var bellSyncMultiplier: Int
get() { mBellSyncMultiplier = mBellSyncMultiplier ?: config.values.get("bellSyncMultiplier", 0); return mBellSyncMultiplier ?: 0 }
@ -18,4 +18,9 @@ class ConfigTimetable(val config: Config) {
var bellSyncDiff: Time?
get() { mBellSyncDiff = mBellSyncDiff ?: config.values.get("bellSyncDiff", null as Time?); return mBellSyncDiff }
set(value) { config.set("bellSyncDiff", value); mBellSyncDiff = value }
private var mCountInSeconds: Boolean? = null
var countInSeconds: Boolean
get() { mCountInSeconds = mCountInSeconds ?: config.values.get("countInSeconds", false); return mCountInSeconds ?: false }
set(value) { config.set("countInSeconds", value); mCountInSeconds = value }
}

View File

@ -8,12 +8,17 @@ import pl.szczodrzynski.edziennik.config.utils.get
import pl.szczodrzynski.edziennik.config.utils.getIntList
import pl.szczodrzynski.edziennik.config.utils.set
class ConfigUI(val config: Config) {
class ConfigUI(private val config: Config) {
private var mTheme: Int? = null
var theme: Int
get() { mTheme = mTheme ?: config.values.get("theme", 1); return mTheme ?: 1 }
set(value) { config.set("theme", value); mTheme = value }
private var mLanguage: String? = null
var language: String?
get() { mLanguage = mLanguage ?: config.values.get("language", null as String?); return mLanguage }
set(value) { config.set("language", value); mLanguage = value }
private var mHeaderBackground: String? = null
var headerBackground: String?
get() { mHeaderBackground = mHeaderBackground ?: config.values.get("headerBackground", null as String?); return mHeaderBackground }
@ -33,4 +38,9 @@ class ConfigUI(val config: Config) {
var miniMenuButtons: List<Int>
get() { mMiniMenuButtons = mMiniMenuButtons ?: config.values.getIntList("miniMenuButtons", listOf()); return mMiniMenuButtons ?: listOf() }
set(value) { config.set("miniMenuButtons", value); mMiniMenuButtons = value }
private var mAgendaViewType: Int? = null
var agendaViewType: Int
get() { mAgendaViewType = mAgendaViewType ?: config.values.get("agendaViewType", 0); return mAgendaViewType ?: 0 }
set(value) { config.set("agendaViewType", value); mAgendaViewType = value }
}

View File

@ -26,6 +26,7 @@ class ProfileConfig(val db: AppDb, val profileId: Int, rawEntries: List<ConfigEn
val values: HashMap<String, String?> = hashMapOf()
val grades by lazy { ProfileConfigGrades(this) }
/*
val sync by lazy { ConfigSync(this) }
val timetable by lazy { ConfigTimetable(this) }

View File

@ -9,7 +9,7 @@ import pl.szczodrzynski.edziennik.config.utils.set
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.Companion.COLOR_MODE_WEIGHTED
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.Companion.YEAR_ALL_GRADES
class ProfileConfigGrades(val config: ProfileConfig) {
class ProfileConfigGrades(private val config: ProfileConfig) {
private var mColorMode: Int? = null
var colorMode: Int
get() { mColorMode = mColorMode ?: config.values.get("gradesColorMode", COLOR_MODE_WEIGHTED); return mColorMode ?: COLOR_MODE_WEIGHTED }

View File

@ -4,16 +4,33 @@
package pl.szczodrzynski.edziennik.config.utils
import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import pl.szczodrzynski.edziennik.App
import pl.szczodrzynski.edziennik.BuildConfig
import pl.szczodrzynski.edziennik.MainActivity
import pl.szczodrzynski.edziennik.api.v2.LOGIN_TYPE_LIBRUS
import pl.szczodrzynski.edziennik.api.v2.LOGIN_TYPE_MOBIDZIENNIK
import pl.szczodrzynski.edziennik.api.v2.LOGIN_TYPE_VULCAN
import pl.szczodrzynski.edziennik.config.Config
import pl.szczodrzynski.edziennik.utils.models.Time
class ConfigMigration(config: Config) {
class ConfigMigration(app: App, config: Config) {
init { config.apply {
val p = app.getSharedPreferences("pl.szczodrzynski.edziennik_profiles", Context.MODE_PRIVATE)
val s = "app.appConfig"
if (dataVersion < 1) {
ui.theme = 1
sync.enabled = true
sync.interval = 60*60; // seconds
ui.miniMenuButtons = listOf(
ui.theme = p.getString("$s.appTheme", null)?.toIntOrNull() ?: 1
sync.enabled = p.getString("$s.registerSyncEnabled", null)?.toBoolean() ?: true
sync.interval = p.getString("$s.registerSyncEnabled", null)?.toIntOrNull() ?: 3600
val oldButtons = p.getString("$s.miniDrawerButtonIds", null)?.let { str ->
str.replace("[\\[\\]]*".toRegex(), "")
.split(",\\s?".toRegex())
.mapNotNull { it.toIntOrNull() }
}
ui.miniMenuButtons = oldButtons ?: listOf(
MainActivity.DRAWER_ITEM_HOME,
MainActivity.DRAWER_ITEM_TIMETABLE,
MainActivity.DRAWER_ITEM_AGENDA,
@ -24,5 +41,44 @@ class ConfigMigration(config: Config) {
)
dataVersion = 1
}
if (dataVersion < 2) {
devModePassword = p.getString("$s.devModePassword", null).fix()
sync.tokenApp = p.getString("$s.fcmToken", null).fix()
timetable.bellSyncMultiplier = p.getString("$s.bellSyncMultiplier", null)?.toIntOrNull() ?: 0
sync.quietHoursStart = p.getString("$s.quietHoursStart", null)?.toLongOrNull() ?: 0
appRateSnackbarTime = p.getString("$s.appRateSnackbarTime", null)?.toLongOrNull() ?: 0
sync.quietHoursEnd = p.getString("$s.quietHoursEnd", null)?.toLongOrNull() ?: 0
timetable.countInSeconds = p.getString("$s.countInSeconds", null)?.toBoolean() ?: false
ui.headerBackground = p.getString("$s.headerBackground", null).fix()
ui.appBackground = p.getString("$s.appBackground", null).fix()
ui.language = p.getString("$s.language", null).fix()
appVersion = p.getString("$s.lastAppVersion", null)?.toIntOrNull() ?: BuildConfig.VERSION_CODE
appInstalledTime = p.getString("$s.appInstalledTime", null)?.toLongOrNull() ?: 0
grades.orderBy = p.getString("$s.gradesOrderBy", null)?.toIntOrNull() ?: 0
sync.quietDuringLessons = p.getString("$s.quietDuringLessons", null)?.toBoolean() ?: false
ui.miniMenuVisible = p.getString("$s.miniDrawerVisible", null)?.toBoolean() ?: false
loginFinished = p.getString("$s.loginFinished", null)?.toBoolean() ?: false
sync.onlyWifi = p.getString("$s.registerSyncOnlyWifi", null)?.toBoolean() ?: false
sync.notifyAboutUpdates = p.getString("$s.notifyAboutUpdates", null)?.toBoolean() ?: true
timetable.bellSyncDiff = p.getString("$s.bellSyncDiff", null)?.let { Gson().fromJson(it, Time::class.java) }
sync.tokenMobidziennikList = listOf()
sync.tokenVulcanList = listOf()
sync.tokenLibrusList = listOf()
val tokens = p.getString("$s.fcmTokens", null)?.let { Gson().fromJson<Map<Int, Pair<String, List<Int>>>>(it, object: TypeToken<Map<Int, Pair<String, List<Int>>>>(){}.type) }
tokens?.forEach {
val token = it.value.first
when (it.key) {
LOGIN_TYPE_MOBIDZIENNIK -> sync.tokenMobidziennik = token
LOGIN_TYPE_VULCAN -> sync.tokenVulcan = token
LOGIN_TYPE_LIBRUS -> sync.tokenLibrus = token
}
}
dataVersion = 2
}
}}
private fun String?.fix(): String? {
return this?.replace("\"", "")?.let { if (it == "null") null else it }
}
}

View File

@ -0,0 +1,26 @@
/*
* Copyright (c) Kuba Szczodrzyński 2019-12-1.
*/
package pl.szczodrzynski.edziennik.config.utils
import android.content.Context
import pl.szczodrzynski.edziennik.App
import pl.szczodrzynski.edziennik.config.Config
class ProfileConfigMigration(app: App, config: Config) {
init { config.apply {
val p = app.getSharedPreferences("pl.szczodrzynski.edziennik_profiles", Context.MODE_PRIVATE)
val s = "app.appConfig"
if (dataVersion < 1) {
//dataVersion = 1
}
if (dataVersion < 2) {
//gradesColorMode do profilu !
//agendaViewType do profilu !
// app.appConfig.dontCountZeroToAverage do profilu !
}
}}
}

View File

@ -1,5 +1,6 @@
package pl.szczodrzynski.edziennik.data.db.modules.profiles;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
@ -24,6 +25,7 @@ public interface ProfileDao {
@Query("SELECT profiles.*, loginStores.loginStoreType, loginStores.loginStoreData FROM profiles LEFT JOIN loginStores ON profiles.loginStoreId = loginStores.loginStoreId WHERE profileId = :profileId")
LiveData<ProfileFull> getById(int profileId);
@Nullable
@Query("SELECT profiles.*, loginStores.loginStoreType, loginStores.loginStoreData FROM profiles LEFT JOIN loginStores ON profiles.loginStoreId = loginStores.loginStoreId WHERE profileId = :profileId")
ProfileFull getFullByIdNow(int profileId);

View File

@ -2,6 +2,7 @@ package pl.szczodrzynski.edziennik.data.db.modules.profiles
import android.content.Context
import androidx.room.ColumnInfo
import androidx.room.Ignore
import com.google.gson.JsonObject
import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_AGENDA
import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_ANNOUNCEMENTS
@ -123,6 +124,9 @@ class ProfileFull : Profile {
constructor(context: Context) : super(context)
@Ignore
constructor(id: Int, name: String, subname: String, loginStoreId: Int) : super(id, name, subname, loginStoreId)
fun canChangeLoginPassword(): Boolean {
return loginStoreType == LOGIN_TYPE_MOBIDZIENNIK || loginStoreType == LOGIN_TYPE_LIBRUS || loginStoreType == LOGIN_TYPE_IUCZNIOWIE
}

View File

@ -90,12 +90,12 @@ public class ServerRequest {
.addParameter("device_id", Settings.Secure.getString(app.getContext().getContentResolver(), Settings.Secure.ANDROID_ID))
.addParameter("device_model", Build.MANUFACTURER+" "+Build.MODEL)
.addParameter("device_os_version", Build.VERSION.RELEASE)
.addParameter("fcm_token", app.appConfig.fcmToken)
.addParameter("fcm_token", app.config.getSync().getTokenApp())
.addParameter("signature", sign(app.signature, timestamp))
.addParameter("signature_timestamp", timestamp)
.addParameter("package_name", "pl.szczodrzynski.edziennik")
.addParameter("source", source)
.addParameter("update_frequency", app.appConfig.registerSyncEnabled ? app.appConfig.registerSyncInterval : -1)
.addParameter("update_frequency", app.config.getSync().getEnabled() ? app.config.getSync().getInterval() : -1)
.post()
.callback(new JsonCallbackHandler() {
@Override
@ -127,12 +127,12 @@ public class ServerRequest {
.addParameter("device_id", Settings.Secure.getString(app.getContext().getContentResolver(), Settings.Secure.ANDROID_ID))
.addParameter("device_model", Build.MANUFACTURER+" "+Build.MODEL)
.addParameter("device_os_version", Build.VERSION.RELEASE)
.addParameter("fcm_token", app.appConfig.fcmToken)
.addParameter("fcm_token", app.config.getSync().getTokenApp())
.addParameter("signature", sign(app.signature, timestamp))
.addParameter("signature_timestamp", timestamp)
.addParameter("package_name", "pl.szczodrzynski.edziennik")
.addParameter("source", source)
.addParameter("update_frequency", app.appConfig.registerSyncEnabled ? app.appConfig.registerSyncInterval : -1)
.addParameter("update_frequency", app.config.getSync().getEnabled() ? app.config.getSync().getInterval() : -1)
.post()
.build()
.execute();

View File

@ -47,9 +47,8 @@ public class MyFirebaseMessagingService extends FirebaseMessagingService {
Log.d(TAG, "New token: "+s);
App app = (App)getApplicationContext();
if (app.appConfig.fcmToken == null || !app.appConfig.fcmToken.equals(s)) {
app.appConfig.fcmToken = s;
app.saveConfig();
if (app.config.getSync().getTokenApp() == null || !app.config.getSync().getTokenApp().equals(s)) {
app.config.getSync().setTokenApp(s);
}
}
@ -198,8 +197,7 @@ public class MyFirebaseMessagingService extends FirebaseMessagingService {
else {
feedbackMessage.sentTime = Long.parseLong(remoteMessage.getData().get("sent_time"));
if (feedbackMessage.text.startsWith("devmode")) {
app.appConfig.devModePassword = feedbackMessage.text.replace("devmode", "");
app.saveConfig("devModePassword");
app.config.setDevModePassword(feedbackMessage.text.replace("devmode", ""));
app.checkDevModePassword();
feedbackMessage.text = "devmode "+(App.devMode ? "allowed" : "disallowed");
}

View File

@ -57,16 +57,16 @@ class SyncWorker(val context: Context, val params: WorkerParameters) : Worker(co
/**
* Cancel any existing sync jobs and schedule a new one.
*
* If [registerSyncEnabled] is not true, just cancel every job.
* If [ConfigSync.enabled] is not true, just cancel every job.
*/
fun rescheduleNext(app: App) {
cancelNext(app)
val enableSync = app.appConfig.registerSyncEnabled
val enableSync = app.config.sync.enabled
if (!enableSync) {
return
}
val onlyWifi = app.appConfig.registerSyncOnlyWifi
val syncInterval = app.appConfig.registerSyncInterval.toLong()
val onlyWifi = app.config.sync.onlyWifi
val syncInterval = app.config.sync.interval.toLong()
val syncAt = System.currentTimeMillis() + syncInterval*1000
d(TAG, "Scheduling work at ${syncAt.formatDate()}")

View File

@ -84,7 +84,7 @@ public class AgendaFragment extends Fragment {
if (app.profile == null)
return inflater.inflate(R.layout.fragment_loading, container, false);
// activity, context and profile is valid
viewType = app.profile.getAgendaViewType();
viewType = app.config.getUi().getAgendaViewType();
if (viewType == AGENDA_DEFAULT) {
b_default = DataBindingUtil.inflate(inflater, R.layout.fragment_agenda_default, container, false);
return b_default.getRoot();
@ -128,8 +128,7 @@ public class AgendaFragment extends Fragment {
.withOnClickListener(v3 -> {
activity.getBottomSheet().close();
viewType = viewType == AGENDA_DEFAULT ? AGENDA_CALENDAR : AGENDA_DEFAULT;
app.profile.setAgendaViewType(viewType);
app.profileSaveAsync();
app.config.getUi().setAgendaViewType(viewType);
activity.reloadTarget();
}),
new BottomSheetSeparatorItem(true),

View File

@ -23,6 +23,7 @@ import java.util.List;
import pl.szczodrzynski.edziennik.App;
import pl.szczodrzynski.edziennik.MainActivity;
import pl.szczodrzynski.edziennik.R;
import pl.szczodrzynski.edziennik.config.ProfileConfigGrades;
import pl.szczodrzynski.edziennik.data.db.modules.grades.Grade;
import pl.szczodrzynski.edziennik.data.db.modules.grades.GradeFull;
import pl.szczodrzynski.edziennik.data.db.modules.subjects.Subject;
@ -32,15 +33,15 @@ import pl.szczodrzynski.edziennik.utils.models.ItemGradesSubjectModel;
import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetPrimaryItem;
import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetSeparatorItem;
import static pl.szczodrzynski.edziennik.config.ConfigGrades.ORDER_BY_DATE_ASC;
import static pl.szczodrzynski.edziennik.config.ConfigGrades.ORDER_BY_DATE_DESC;
import static pl.szczodrzynski.edziennik.config.ConfigGrades.ORDER_BY_SUBJECT_ASC;
import static pl.szczodrzynski.edziennik.data.db.modules.metadata.Metadata.TYPE_GRADE;
import static pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.YEAR_1_AVG_2_AVG;
import static pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.YEAR_1_AVG_2_SEM;
import static pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.YEAR_1_SEM_2_AVG;
import static pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.YEAR_1_SEM_2_SEM;
import static pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.YEAR_ALL_GRADES;
import static pl.szczodrzynski.edziennik.utils.models.AppConfig.ORDER_BY_DATE_ASC;
import static pl.szczodrzynski.edziennik.utils.models.AppConfig.ORDER_BY_DATE_DESC;
import static pl.szczodrzynski.edziennik.utils.models.AppConfig.ORDER_BY_SUBJECT_ASC;
public class GradesFragment extends Fragment {
@ -135,12 +136,12 @@ public class GradesFragment extends Fragment {
.withIcon(CommunityMaterial.Icon2.cmd_palette_outline)
.withOnClickListener(v3 -> {
activity.getBottomSheet().close();
ProfileConfigGrades config = app.config.getFor(app.profileId).getGrades();
new MaterialDialog.Builder(activity)
.title(R.string.dialog_grades_color_mode_title)
.items(R.array.dialog_grades_color_modes)
.itemsCallbackSingleChoice(app.profile.getGradeColorMode(), (dialog, view1, which, text) -> {
app.profile.setGradeColorMode(which);
app.profileSaveAsync();
.itemsCallbackSingleChoice(config.getColorMode(), (dialog, view1, which, text) -> {
config.setColorMode(which);
activity.reloadTarget();
return true;
})
@ -154,9 +155,8 @@ public class GradesFragment extends Fragment {
new MaterialDialog.Builder(activity)
.title(R.string.dialog_grades_sort_title)
.items(R.array.dialog_grades_sort_modes)
.itemsCallbackSingleChoice(app.appConfig.gradesOrderBy, (dialog, view1, which, text) -> {
app.appConfig.gradesOrderBy = which;
app.saveConfig("gradesOrderBy");
.itemsCallbackSingleChoice(app.config.getGrades().getOrderBy(), (dialog, view1, which, text) -> {
app.config.getGrades().setOrderBy(which);
activity.reloadTarget();
return true;
})
@ -228,13 +228,13 @@ public class GradesFragment extends Fragment {
long finalExpandSubjectId = expandSubjectId;
String orderBy;
if (app.appConfig.gradesOrderBy == ORDER_BY_SUBJECT_ASC) {
if (app.config.getGrades().getOrderBy() == ORDER_BY_SUBJECT_ASC) {
orderBy = "subjectLongName ASC, addedDate DESC";
}
else if (app.appConfig.gradesOrderBy == ORDER_BY_DATE_DESC) {
else if (app.config.getGrades().getOrderBy() == ORDER_BY_DATE_DESC) {
orderBy = "addedDate DESC";
}
else if (app.appConfig.gradesOrderBy == ORDER_BY_DATE_ASC) {
else if (app.config.getGrades().getOrderBy() == ORDER_BY_DATE_ASC) {
orderBy = "addedDate ASC";
}
else {
@ -247,11 +247,13 @@ public class GradesFragment extends Fragment {
subjectList = new ArrayList<>();
ProfileConfigGrades config = app.config.getFor(app.profileId).getGrades();
// now we have all grades from the newest to the oldest
for (GradeFull grade: grades) {
ItemGradesSubjectModel model = ItemGradesSubjectModel.searchModelBySubjectId(subjectList, grade.subjectId);
if (model == null) {
model = new ItemGradesSubjectModel(app.profile, new Subject(App.profileId, grade.subjectId, grade.subjectLongName, grade.subjectShortName), new ArrayList<>(), new ArrayList<>());//ItemGradesSubjectModel.searchModelBySubjectId(subjectList, grade.subjectId);
model = new ItemGradesSubjectModel(app.profile, new Subject(app.profileId, grade.subjectId, grade.subjectLongName, grade.subjectShortName), new ArrayList<>(), new ArrayList<>());//ItemGradesSubjectModel.searchModelBySubjectId(subjectList, grade.subjectId);
subjectList.add(model);
if (model.subject != null && model.subject.id == finalExpandSubjectId) {
model.expandView = true;
@ -303,7 +305,7 @@ public class GradesFragment extends Fragment {
// do not show *normal* grades with negative weight - these are historical grades - Iuczniowie
continue;
}
if (app.appConfig.dontCountZeroToAverage && grade.name.equals("0")) {
if (!config.getCountZeroToAvg() && grade.name.equals("0")) {
weight = 0;
}
float valueWeighted = grade.value * weight;

View File

@ -28,15 +28,15 @@ import java.text.DecimalFormat;
import java.util.List;
import pl.szczodrzynski.edziennik.App;
import pl.szczodrzynski.edziennik.R;
import pl.szczodrzynski.edziennik.MainActivity;
import pl.szczodrzynski.edziennik.R;
import pl.szczodrzynski.edziennik.data.db.AppDb;
import pl.szczodrzynski.edziennik.data.db.modules.grades.GradeFull;
import pl.szczodrzynski.edziennik.data.db.modules.subjects.Subject;
import pl.szczodrzynski.edziennik.utils.models.ItemGradesSubjectModel;
import pl.szczodrzynski.edziennik.utils.Anim;
import pl.szczodrzynski.edziennik.utils.Colors;
import pl.szczodrzynski.edziennik.utils.Utils;
import pl.szczodrzynski.edziennik.utils.models.ItemGradesSubjectModel;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
@ -219,7 +219,7 @@ public class GradesSubjectAdapter extends ArrayAdapter<ItemGradesSubjectModel> i
layoutParams.setMargins(0, 0, _5dp, 0);
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
int maxWidthPx = displayMetrics.widthPixels - Utils.dpToPx((app.appConfig.miniDrawerVisible ? 72 : 0)/*miniDrawer size*/ + 8 + 8/*left and right offsets*/ + 24/*ellipsize width*/);
int maxWidthPx = displayMetrics.widthPixels - Utils.dpToPx((app.config.getUi().getMiniMenuVisible() ? 72 : 0)/*miniDrawer size*/ + 8 + 8/*left and right offsets*/ + 24/*ellipsize width*/);
int totalWidthPx = 0;
boolean ellipsized = false;

View File

@ -13,12 +13,12 @@ import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import pl.szczodrzynski.edziennik.*
import pl.szczodrzynski.edziennik.databinding.FragmentGradesEditorBinding
import pl.szczodrzynski.edziennik.data.db.modules.grades.Grade
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.Companion.YEAR_1_AVG_2_AVG
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.Companion.YEAR_1_AVG_2_SEM
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.Companion.YEAR_1_SEM_2_AVG
import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.Companion.YEAR_ALL_GRADES
import pl.szczodrzynski.edziennik.databinding.FragmentGradesEditorBinding
import pl.szczodrzynski.edziennik.utils.Colors
import pl.szczodrzynski.edziennik.utils.Themes
import java.text.DecimalFormat
@ -34,6 +34,8 @@ class GradesEditorFragment : Fragment() {
private val navController: NavController by lazy { Navigation.findNavController(b.root) }
*/
private val config by lazy { app.config.getFor(App.profileId).grades }
private var subjectId: Long = -1
private var semester: Int = 1
@ -108,7 +110,7 @@ class GradesEditorFragment : Fragment() {
continue
}
var weight = editorGrade.weight
if (app.appConfig.dontCountZeroToAverage && editorGrade.name == "0") {
if (!config.countZeroToAvg && editorGrade.name == "0") {
weight = 0f
}
val value = editorGrade.value * weight
@ -173,7 +175,7 @@ class GradesEditorFragment : Fragment() {
averageSemester = 0f
for (editorGrade in editorGrades) {
var weight = editorGrade.weight
if (app.appConfig.dontCountZeroToAverage && editorGrade.name == "0") {
if (!config.countZeroToAvg && editorGrade.name == "0") {
weight = 0f
}
val value = editorGrade.value * weight
@ -216,7 +218,7 @@ class GradesEditorFragment : Fragment() {
continue
}
var weight = grade.weight
if (app.appConfig.dontCountZeroToAverage && grade.name == "0") {
if (!config.countZeroToAvg && grade.name == "0") {
weight = 0f
}
val value = grade.value * weight

View File

@ -49,17 +49,17 @@ public class CounterActivity extends AppCompatActivity {
Time now = Time.getNow();
Time syncedNow = now;
//Time updateDiff = null;
if (app.appConfig.bellSyncDiff != null) {
if (app.appConfig.bellSyncMultiplier < 0) {
if (app.config.getTimetable().getBellSyncDiff() != null) {
if (app.config.getTimetable().getBellSyncMultiplier() < 0) {
// the bell is too fast, need to step further to go with it
// add some time
syncedNow = Time.sum(now, app.appConfig.bellSyncDiff);
syncedNow = Time.sum(now, app.config.getTimetable().getBellSyncDiff());
//Toast.makeText(c, "Bell sync diff is "+app.appConfig.bellSyncDiff.getStringHMS()+"\n\n Synced now is "+syncedNow.getStringHMS(), Toast.LENGTH_LONG).show();
}
if (app.appConfig.bellSyncMultiplier > 0) {
if (app.config.getTimetable().getBellSyncMultiplier() > 0) {
// the bell is delayed, need to roll the "now" time back
// subtract some time
syncedNow = Time.diff(now, app.appConfig.bellSyncDiff);
syncedNow = Time.diff(now, app.config.getTimetable().getBellSyncDiff());
}
}
@ -153,7 +153,7 @@ public class CounterActivity extends AppCompatActivity {
private short counterType = TIME_LEFT;
private long updateCounter(Time syncedNow) {
Time diff = Time.diff(counterTarget, syncedNow);
b.timeLeft.setText(counterType == TIME_TILL ? HomeFragment.timeTill(app, diff, app.appConfig.countInSeconds, "\n") : HomeFragment.timeLeft(app, diff, app.appConfig.countInSeconds, "\n"));
b.timeLeft.setText(counterType == TIME_TILL ? HomeFragment.timeTill(app, diff, app.config.getTimetable().getCountInSeconds(), "\n") : HomeFragment.timeLeft(app, diff, app.config.getTimetable().getCountInSeconds(), "\n"));
return updateInterval(app, diff);
}

View File

@ -310,7 +310,7 @@ public class HomeFragment extends Fragment {
public static long updateInterval(App app, Time diff) {
//Log.d(TAG, "Millis is "+System.currentTimeMillis() % 1000+", update in "+(1000-(System.currentTimeMillis() % 1000)));
if (app.appConfig.countInSeconds) {
if (app.config.getTimetable().getCountInSeconds()) {
return 1000-(System.currentTimeMillis() % 1000);
}
if (diff.minute > 10) {
@ -587,7 +587,7 @@ public class HomeFragment extends Fragment {
private void configCardGrades(Context c, LayoutInflater layoutInflater, Activity a, ViewGroup insertPoint) {
View root = layoutInflater.inflate(R.layout.card_grades, null);
DisplayMetrics displayMetrics = c.getResources().getDisplayMetrics();
updateCardGrades(c, a, root, displayMetrics.widthPixels - Utils.dpToPx((app.appConfig.miniDrawerVisible ? 72 : 0)/*miniDrawer size*/ + 24 + 24/*left and right offsets*/ + 16/*ellipsize width*/));
updateCardGrades(c, a, root, displayMetrics.widthPixels - Utils.dpToPx((app.config.getUi().getMiniMenuVisible() ? 72 : 0)/*miniDrawer size*/ + 24 + 24/*left and right offsets*/ + 16/*ellipsize width*/));
insertPoint.addView(root, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}

View File

@ -79,7 +79,7 @@ class HomeFragmentV2 : Fragment(), CoroutineScope {
.withOnClickListener(OnClickListener {
activity.bottomSheet.close()
StudentNumberDialog(activity, app.profile) {
app.profileSaveAsync()
app.profileSave()
}
}),
BottomSheetSeparatorItem(true),

View File

@ -74,8 +74,8 @@ class HomeTimetableCard(
.title(R.string.bell_sync_title)
.content(app.getString(R.string.bell_sync_howto, bellSyncTime!!.stringHM).toString() +
when {
app.appConfig.bellSyncDiff != null -> app.getString(R.string.bell_sync_current_dialog,
(if (app.appConfig.bellSyncMultiplier == -1) "-" else "+") + app.appConfig.bellSyncDiff.stringHMS)
app.config.timetable.bellSyncDiff != null -> app.getString(R.string.bell_sync_current_dialog,
(if (app.config.timetable.bellSyncMultiplier == -1) "-" else "+") + app.config.timetable.bellSyncDiff?.stringHMS)
else -> ""
})
.positiveText(R.string.ok)
@ -83,9 +83,8 @@ class HomeTimetableCard(
.neutralText(R.string.reset)
.onPositive { _, _: DialogAction? ->
val bellDiff = Time.diff(Time.getNow(), bellSyncTime)
app.appConfig.bellSyncDiff = bellDiff
app.appConfig.bellSyncMultiplier = if (bellSyncTime!!.value > Time.getNow().value) -1 else 1
app.saveConfig("bellSyncDiff", "bellSyncMultiplier")
app.config.timetable.bellSyncDiff = bellDiff
app.config.timetable.bellSyncMultiplier = if (bellSyncTime!!.value > Time.getNow().value) -1 else 1
MaterialDialog.Builder(activity)
.title(R.string.bell_sync_title)
@ -100,8 +99,8 @@ class HomeTimetableCard(
.positiveText(R.string.yes)
.negativeText(R.string.no)
.onPositive { _, _ ->
app.appConfig.bellSyncDiff = null
app.appConfig.bellSyncMultiplier = 0
app.config.timetable.bellSyncDiff = null
app.config.timetable.bellSyncMultiplier = 0
app.saveConfig("bellSyncDiff", "bellSyncMultiplier")
}
.show()
@ -129,10 +128,10 @@ class HomeTimetableCard(
val now = Time.getNow()
val syncedNow: Time = when (app.appConfig.bellSyncDiff != null) {
val syncedNow: Time = when (app.config.timetable.bellSyncDiff != null) {
true -> when {
app.appConfig.bellSyncMultiplier < 0 -> Time.sum(now, app.appConfig.bellSyncDiff)
app.appConfig.bellSyncMultiplier > 0 -> Time.diff(now, app.appConfig.bellSyncDiff)
app.config.timetable.bellSyncMultiplier < 0 -> Time.sum(now, app.config.timetable.bellSyncDiff)
app.config.timetable.bellSyncMultiplier > 0 -> Time.diff(now, app.config.timetable.bellSyncDiff)
else -> now
}
else -> now
@ -148,8 +147,8 @@ class HomeTimetableCard(
private fun updateCounter(syncedNow: Time): Long {
val diff = Time.diff(counterTarget, syncedNow)
b.cardTimetableTimeLeft.text = when (counterType) {
TIME_TILL -> HomeFragment.timeTill(app, diff, app.appConfig.countInSeconds)
else -> HomeFragment.timeLeft(app, diff, app.appConfig.countInSeconds)
TIME_TILL -> HomeFragment.timeTill(app, diff, app.config.timetable.countInSeconds)
else -> HomeFragment.timeLeft(app, diff, app.config.timetable.countInSeconds)
}
bellSyncTime = counterTarget.clone()
b.cardTimetableFullscreenCounter.visibility = View.VISIBLE

View File

@ -77,17 +77,16 @@ public class HomeTimetableCardOld {
new MaterialDialog.Builder(a)
.title(R.string.bell_sync_title)
.content(app.getString(R.string.bell_sync_howto, bellSyncTime.getStringHM())+
(app.appConfig.bellSyncDiff != null ?
""+app.getString(R.string.bell_sync_current_dialog, (app.appConfig.bellSyncMultiplier == -1 ? "-" : "+")+app.appConfig.bellSyncDiff.getStringHMS())
(app.config.getTimetable().getBellSyncDiff() != null ?
""+app.getString(R.string.bell_sync_current_dialog, (app.config.getTimetable().getBellSyncMultiplier() == -1 ? "-" : "+")+app.config.getTimetable().getBellSyncDiff().getStringHMS())
: ""))
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.neutralText(R.string.reset)
.onPositive((dialog, which) -> {
Time bellDiff = Time.diff(Time.getNow(), bellSyncTime);
app.appConfig.bellSyncDiff = bellDiff;
app.appConfig.bellSyncMultiplier = (bellSyncTime.getValue() > Time.getNow().getValue() ? -1 : 1);
app.saveConfig("bellSyncDiff", "bellSyncMultiplier");
app.config.getTimetable().setBellSyncDiff(bellDiff);
app.config.getTimetable().setBellSyncMultiplier(bellSyncTime.getValue() > Time.getNow().getValue() ? -1 : 1);
new MaterialDialog.Builder(a)
.title(R.string.bell_sync_title)
.content(app.getString(R.string.bell_sync_results, (bellSyncTime.getValue() > Time.getNow().getValue() ? "-" : "+"), bellDiff.getStringHMS()))
@ -101,9 +100,8 @@ public class HomeTimetableCardOld {
.positiveText(R.string.yes)
.negativeText(R.string.no)
.onPositive(((dialog1, which1) -> {
app.appConfig.bellSyncDiff = null;
app.appConfig.bellSyncMultiplier = 0;
app.saveConfig("bellSyncDiff", "bellSyncMultiplier");
app.config.getTimetable().setBellSyncDiff(null);
app.config.getTimetable().setBellSyncMultiplier(0);
}))
.show();
})
@ -125,17 +123,17 @@ public class HomeTimetableCardOld {
Time now = Time.getNow();
Time syncedNow = now;
//Time updateDiff = null;
if (app.appConfig.bellSyncDiff != null) {
if (app.appConfig.bellSyncMultiplier < 0) {
if (app.config.getTimetable().getBellSyncDiff() != null) {
if (app.config.getTimetable().getBellSyncMultiplier() < 0) {
// the bell is too fast, need to step further to go with it
// add some time
syncedNow = Time.sum(now, app.appConfig.bellSyncDiff);
syncedNow = Time.sum(now, app.config.getTimetable().getBellSyncDiff());
//Toast.makeText(c, "Bell sync diff is "+app.appConfig.bellSyncDiff.getStringHMS()+"\n\n Synced now is "+syncedNow.getStringHMS(), Toast.LENGTH_LONG).show();
}
if (app.appConfig.bellSyncMultiplier > 0) {
if (app.config.getTimetable().getBellSyncMultiplier() > 0) {
// the bell is delayed, need to roll the "now" time back
// subtract some time
syncedNow = Time.diff(now, app.appConfig.bellSyncDiff);
syncedNow = Time.diff(now, app.config.getTimetable().getBellSyncDiff());
}
}
@ -230,7 +228,7 @@ public class HomeTimetableCardOld {
private short counterType = TIME_TILL;
private long updateCounter(Time syncedNow) {
Time diff = Time.diff(counterTarget, syncedNow);
b.cardTimetableTimeLeft.setText(counterType == TIME_TILL ? HomeFragment.timeTill(app, diff, app.appConfig.countInSeconds) : HomeFragment.timeLeft(app, diff, app.appConfig.countInSeconds));
b.cardTimetableTimeLeft.setText(counterType == TIME_TILL ? HomeFragment.timeTill(app, diff, app.config.getTimetable().getCountInSeconds()) : HomeFragment.timeLeft(app, diff, app.config.getTimetable().getCountInSeconds()));
bellSyncTime = counterTarget;
b.cardTimetableFullscreenCounter.setVisibility(View.VISIBLE);
return updateInterval(app, diff);

View File

@ -116,7 +116,7 @@ class HomeGradesCard(
var totalWidth = 0
val maxWidth = (app.resources.displayMetrics.widthPixels -
Utils.dpToPx((if (app.appConfig.miniDrawerVisible) 72 else 0) /*miniDrawer size*/ +
Utils.dpToPx((if (app.config.ui.miniMenuVisible) 72 else 0) /*miniDrawer size*/ +
24 + 24 /*left and right offsets*/ +
16 /*ellipsize width*/)) / 1.5f

View File

@ -80,9 +80,9 @@ class HomeTimetableCard(
.sizeDp(20))
// get current bell-sync params
if (app.appConfig.bellSyncDiff != null) {
bellSyncDiffMillis = (app.appConfig.bellSyncDiff.hour * 60 * 60 * 1000 + app.appConfig.bellSyncDiff.minute * 60 * 1000 + app.appConfig.bellSyncDiff.second * 1000).toLong()
bellSyncDiffMillis *= app.appConfig.bellSyncMultiplier.toLong()
app.config.timetable.bellSyncDiff?.let {
bellSyncDiffMillis = (it.hour * 60 * 60 * 1000 + it.minute * 60 * 1000 + it.second * 1000).toLong()
bellSyncDiffMillis *= app.config.timetable.bellSyncMultiplier.toLong()
bellSyncDiffMillis *= -1
}

View File

@ -78,7 +78,6 @@ public class ChangelogIntroActivity extends IntroActivity {
.build());
}*/
app.appConfig.lastAppVersion = BuildConfig.VERSION_CODE;
app.appConfig.savePending = true;
app.config.setAppVersion(BuildConfig.VERSION_CODE);
}
}

View File

@ -91,9 +91,8 @@ public class LoginActivity extends AppCompatActivity {
app = (App) getApplication();
if (!app.appConfig.loginFinished) {
app.appConfig.miniDrawerVisible = getResources().getConfiguration().smallestScreenWidthDp > 480;
app.saveConfig("miniDrawerVisible");
if (!app.config.getLoginFinished()) {
app.config.getUi().setMiniMenuVisible(getResources().getConfiguration().smallestScreenWidthDp > 480);
}
/*b.getRoot().addOnLayoutChangeListener(((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {

View File

@ -59,7 +59,7 @@ public class LoginChooserFragment extends Fragment {
b.cancelButton.setVisibility(View.VISIBLE);
b.cancelButton.setOnClickListener((v -> nav.navigateUp()));
}
else if (app.appConfig.loginFinished) {
else if (app.config.getLoginFinished()) {
// we are navigated here from AppDrawer
b.cancelButton.setVisibility(View.VISIBLE);
b.cancelButton.setOnClickListener((v -> {

View File

@ -101,12 +101,11 @@ class LoginSyncFragment : Fragment() {
d(TAG, loginStore.toString())
}*/
if (app.appConfig.loginFinished) {
if (app.config.loginFinished) {
LoginFinishFragment.firstRun = false
} else {
LoginFinishFragment.firstRun = true
app.appConfig.loginFinished = true
app.saveConfig("loginFinished")
app.config.loginFinished = true
}
LoginFinishFragment.firstProfileId = firstProfileId
@ -140,7 +139,8 @@ class LoginSyncFragment : Fragment() {
EventType(profileId, TYPE_INFORMATION.toLong(), getString(R.string.event_information), COLOR_INFORMATION)
)
app.db.eventTypeDao().addAll(typeList)
app.profileSaveFull(profile, loginStore)
app.db.profileDao().add(profile)
app.db.loginStoreDao().add(loginStore)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

View File

@ -1,10 +1,5 @@
package pl.szczodrzynski.edziennik.ui.modules.messages;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
@ -12,12 +7,9 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
@ -27,17 +19,13 @@ import com.mikepenz.iconics.IconicsColor;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.IconicsSize;
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial;
import com.theartofdev.edmodo.cropper.CropImage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import pl.szczodrzynski.edziennik.App;
@ -49,8 +37,6 @@ import pl.szczodrzynski.edziennik.ui.modules.error.ErrorDialog;
import pl.szczodrzynski.edziennik.utils.Themes;
import pl.szczodrzynski.edziennik.utils.Utils;
import static android.app.Activity.RESULT_OK;
import static pl.szczodrzynski.edziennik.utils.Utils.getResizedBitmap;
import static pl.szczodrzynski.edziennik.utils.Utils.getStringFromFile;
import static pl.szczodrzynski.edziennik.utils.Utils.readableFileSize;
@ -523,69 +509,6 @@ public class MessagesDetailsFragment extends Fragment {
super.onStop();
EventBus.getDefault().unregister(this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
File photoFile = new File(uri.getPath());
File destFile = new File(getContext().getFilesDir(),"teacher_"+message.senderId+".jpg");
if (destFile.exists()) {
destFile.delete();
destFile = new File(getContext().getFilesDir(),"teacher_"+message.senderId+".jpg");
}
if (result.getCropRect().width() > 512) {
Bitmap bigImage = BitmapFactory.decodeFile(uri.getPath());
Bitmap smallImage = getResizedBitmap(bigImage, 512, 512);
try (FileOutputStream out = new FileOutputStream(destFile)) {
smallImage.compress(Bitmap.CompressFormat.JPEG, 80, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
Bitmap profileImage;
profileImage = BitmapFactory.decodeFile(destFile.getAbsolutePath());
profileImage = ThumbnailUtils.extractThumbnail(profileImage, Math.min(profileImage.getWidth(), profileImage.getHeight()), Math.min(profileImage.getWidth(), profileImage.getHeight()));
RoundedBitmapDrawable roundDrawable = RoundedBitmapDrawableFactory.create(app.getResources(), profileImage);
roundDrawable.setCircular(true);
b.messageProfileImage.setImageDrawable(roundDrawable);
if (app.appConfig.teacherImages == null) {
app.appConfig.teacherImages = new HashMap<>();
}
app.appConfig.teacherImages.put(message.senderId, true);
app.saveConfig("teacherImages");
if (photoFile.exists()) {
photoFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
if (photoFile.renameTo(destFile)) {
// success
Bitmap profileImage;
profileImage = BitmapFactory.decodeFile(destFile.getAbsolutePath());
profileImage = ThumbnailUtils.extractThumbnail(profileImage, Math.min(profileImage.getWidth(), profileImage.getHeight()), Math.min(profileImage.getWidth(), profileImage.getHeight()));
RoundedBitmapDrawable roundDrawable = RoundedBitmapDrawableFactory.create(app.getResources(), profileImage);
roundDrawable.setCircular(true);
b.messageProfileImage.setImageDrawable(roundDrawable);
if (app.appConfig.teacherImages == null) {
app.appConfig.teacherImages = new HashMap<>();
}
app.appConfig.teacherImages.put(message.senderId, true);
app.saveConfig("teacherImages");
}
else {
// not this time
Toast.makeText(app, R.string.error_occured, Toast.LENGTH_LONG).show();
}
}
}
}
}
/*if (message.type == TYPE_RECEIVED) {

View File

@ -296,12 +296,11 @@ public class SettingsNewFragment extends MaterialAboutFragment {
new MaterialDialog.Builder(activity)
.title(R.string.settings_theme_theme_text)
.items(Themes.INSTANCE.getThemeNames(activity))
.itemsCallbackSingleChoice(app.appConfig.appTheme, (dialog, itemView, which, text) -> {
if (app.appConfig.appTheme == which)
.itemsCallbackSingleChoice(app.config.getUi().getTheme(), (dialog, itemView, which, text) -> {
if (app.config.getUi().getTheme() == which)
return true;
app.appConfig.appTheme = which;
Themes.INSTANCE.setThemeInt(app.appConfig.appTheme);
app.saveConfig("appTheme");
app.config.getUi().setTheme(which);
Themes.INSTANCE.setThemeInt(app.config.getUi().getTheme());
activity.recreate();
return true;
})
@ -318,14 +317,13 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.appConfig.miniDrawerVisible)
.setChecked(app.config.getUi().getMiniMenuVisible())
.setOnChangeAction((isChecked, tag) -> {
// 0,1 1
// 0,0 0
// 1,1 0
// 1,0 1
app.appConfig.miniDrawerVisible = isChecked;
app.saveConfig("miniDrawerVisible");
app.config.getUi().setMiniMenuVisible(isChecked);
activity.getNavView().drawer.setMiniDrawerVisiblePortrait(isChecked);
return true;
})
@ -409,7 +407,7 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
if (app.appConfig.headerBackground != null) {
if (app.config.getUi().getHeaderBackground() != null) {
new MaterialDialog.Builder(activity)
.title(R.string.what_do_you_want_to_do)
.items(getString(R.string.settings_theme_drawer_header_dialog_set), getString(R.string.settings_theme_drawer_header_dialog_restore))
@ -418,12 +416,11 @@ public class SettingsNewFragment extends MaterialAboutFragment {
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 22);
} else {
MainActivity ac = (MainActivity) getActivity();
app.appConfig.headerBackground = null;
app.config.getUi().setHeaderBackground(null);
if (ac != null) {
ac.getDrawer().setAccountHeaderBackground(null);
ac.getDrawer().open();
}
app.saveConfig("headerBackground");
}
})
.show();
@ -444,7 +441,7 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
if (app.appConfig.appBackground != null) {
if (app.config.getUi().getAppBackground() != null) {
new MaterialDialog.Builder(activity)
.title(R.string.what_do_you_want_to_do)
.items(getString(R.string.settings_theme_app_background_dialog_set), getString(R.string.settings_theme_app_background_dialog_restore))
@ -452,8 +449,7 @@ public class SettingsNewFragment extends MaterialAboutFragment {
if (position == 0) {
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 23);
} else {
app.appConfig.appBackground = null;
app.saveConfig("appBackground");
app.config.getUi().setAppBackground(null);
activity.recreate();
}
})
@ -479,25 +475,25 @@ public class SettingsNewFragment extends MaterialAboutFragment {
|__*/
private String getSyncCardIntervalSubText() {
if (app.appConfig.registerSyncInterval < 60 * 60)
if (app.config.getSync().getInterval() < 60 * 60)
return getString(
R.string.settings_sync_sync_interval_subtext_format,
HomeFragment.plural(activity, R.plurals.time_till_minutes, app.appConfig.registerSyncInterval / 60)
HomeFragment.plural(activity, R.plurals.time_till_minutes, app.config.getSync().getInterval() / 60)
);
return getString(
R.string.settings_sync_sync_interval_subtext_format,
HomeFragment.plural(activity, R.plurals.time_till_hours, app.appConfig.registerSyncInterval / 60 / 60) +
(app.appConfig.registerSyncInterval / 60 % 60 == 0 ?
HomeFragment.plural(activity, R.plurals.time_till_hours, app.config.getSync().getInterval() / 60 / 60) +
(app.config.getSync().getInterval() / 60 % 60 == 0 ?
"" :
" " + HomeFragment.plural(activity, R.plurals.time_till_minutes, app.appConfig.registerSyncInterval / 60 % 60)
" " + HomeFragment.plural(activity, R.plurals.time_till_minutes, app.config.getSync().getInterval() / 60 % 60)
)
);
}
private String getSyncCardQuietHoursSubText() {
return getString(
app.appConfig.quietHoursStart >= app.appConfig.quietHoursEnd ? R.string.settings_sync_quiet_hours_subtext_next_day_format : R.string.settings_sync_quiet_hours_subtext_format,
Time.fromMillis(Math.abs(app.appConfig.quietHoursStart)).getStringHM(),
Time.fromMillis(app.appConfig.quietHoursEnd).getStringHM()
app.config.getSync().getQuietHoursStart() >= app.config.getSync().getQuietHoursEnd() ? R.string.settings_sync_quiet_hours_subtext_next_day_format : R.string.settings_sync_quiet_hours_subtext_format,
Time.fromMillis(Math.abs(app.config.getSync().getQuietHoursStart())).getStringHM(),
Time.fromMillis(app.config.getSync().getQuietHoursEnd()).getStringHM()
);
}
private MaterialAboutItem getSyncCardWifiItem() {
@ -509,10 +505,9 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.appConfig.registerSyncOnlyWifi)
.setChecked(app.config.getSync().getOnlyWifi())
.setOnChangeAction((isChecked, tag) -> {
app.appConfig.registerSyncOnlyWifi = isChecked;
app.saveConfig("registerSyncOnlyWifi");
app.config.getSync().setOnlyWifi(isChecked);
SyncWorker.Companion.rescheduleNext(app);
return true;
});
@ -532,7 +527,7 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.color(IconicsColor.colorInt(iconColor))
);
syncCardIntervalItem.setSubTextChecked(getSyncCardIntervalSubText());
syncCardIntervalItem.setChecked(app.appConfig.registerSyncEnabled);
syncCardIntervalItem.setChecked(app.config.getSync().getEnabled());
syncCardIntervalItem.setOnClickAction(() -> {
List<CharSequence> intervalNames = new ArrayList<>();
if (App.devMode && false) {
@ -562,39 +557,37 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.title(getString(R.string.settings_sync_sync_interval_dialog_title))
.content(getString(R.string.settings_sync_sync_interval_dialog_text))
.items(intervalNames)
.itemsCallbackSingleChoice(intervals.indexOf(app.appConfig.registerSyncInterval), (dialog, itemView, which, text) -> {
app.appConfig.registerSyncInterval = intervals.get(which);
.itemsCallbackSingleChoice(intervals.indexOf(app.config.getSync().getInterval()), (dialog, itemView, which, text) -> {
app.config.getSync().setInterval(intervals.get(which));
syncCardIntervalItem.setSubTextChecked(getSyncCardIntervalSubText());
syncCardIntervalItem.setChecked(true);
if (!app.appConfig.registerSyncEnabled) {
if (!app.config.getSync().getEnabled()) {
addCardItem(CARD_SYNC, 1, getSyncCardWifiItem());
}
else {
refreshMaterialAboutList();
}
app.appConfig.registerSyncEnabled = true;
app.config.getSync().setEnabled(true);
// app.appConfig modifications have to surround syncCardIntervalItem and those ifs
app.saveConfig("registerSyncInterval", "registerSyncEnabled");
SyncWorker.Companion.rescheduleNext(app);
return true;
})
.show();
});
syncCardIntervalItem.setOnChangeAction((isChecked, tag) -> {
if (isChecked && !app.appConfig.registerSyncEnabled) {
if (isChecked && !app.config.getSync().getEnabled()) {
addCardItem(CARD_SYNC, 1, getSyncCardWifiItem());
}
else if (!isChecked) {
removeCardItem(CARD_SYNC, 1);
}
app.appConfig.registerSyncEnabled = isChecked;
app.saveConfig("registerSyncEnabled");
app.config.getSync().setEnabled(isChecked);
SyncWorker.Companion.rescheduleNext(app);
return true;
});
items.add(syncCardIntervalItem);
if (app.appConfig.registerSyncEnabled) {
if (app.config.getSync().getEnabled()) {
items.add(getSyncCardWifiItem());
}
@ -624,7 +617,7 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
);
syncCardQuietHoursItem.setChecked(app.appConfig.quietHoursStart > 0);
syncCardQuietHoursItem.setChecked(app.config.getSync().getQuietHoursStart() > 0);
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
syncCardQuietHoursItem.setOnClickAction(() -> {
new MaterialDialog.Builder(activity)
@ -636,11 +629,10 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.itemsCallback((dialog, itemView, position, text) -> {
if (position == 0) {
// set beginning
Time time = Time.fromMillis(Math.abs(app.appConfig.quietHoursStart));
Time time = Time.fromMillis(Math.abs(app.config.getSync().getQuietHoursStart()));
TimePickerDialog.newInstance((v2, hourOfDay, minute, second) -> {
// if it's disabled, it'll be enabled automatically
app.appConfig.quietHoursStart = new Time(hourOfDay, minute, second).getInMillis();
app.saveConfig("quietHoursStart");
app.config.getSync().setQuietHoursStart(new Time(hourOfDay, minute, second).getInMillis());
syncCardQuietHoursItem.setChecked(true);
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
refreshMaterialAboutList();
@ -648,15 +640,13 @@ public class SettingsNewFragment extends MaterialAboutFragment {
}
else {
// set end
Time time = Time.fromMillis(app.appConfig.quietHoursEnd);
Time time = Time.fromMillis(app.config.getSync().getQuietHoursEnd());
TimePickerDialog.newInstance((v2, hourOfDay, minute, second) -> {
if (app.appConfig.quietHoursStart < 0) {
if (app.config.getSync().getQuietHoursStart() < 0) {
// if it's disabled, enable
app.appConfig.quietHoursStart *= -1;
app.saveConfig("quietHoursStart");
app.config.getSync().setQuietHoursStart(-1 * app.config.getSync().getQuietHoursStart());
}
app.appConfig.quietHoursEnd = new Time(hourOfDay, minute, second).getInMillis();
app.saveConfig("quietHoursEnd");
app.config.getSync().setQuietHoursEnd(new Time(hourOfDay, minute, second).getInMillis());
syncCardQuietHoursItem.setChecked(true);
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
refreshMaterialAboutList();
@ -666,20 +656,17 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.show();
});
syncCardQuietHoursItem.setOnChangeAction((isChecked, tag) -> {
if (isChecked && app.appConfig.quietHoursStart < 0) {
app.appConfig.quietHoursStart *= -1;
app.saveConfig("quietHoursStart");
if (isChecked && app.config.getSync().getQuietHoursStart() < 0) {
app.config.getSync().setQuietHoursStart(app.config.getSync().getQuietHoursStart() * -1);
}
else if (!isChecked && app.appConfig.quietHoursStart > 0) {
app.appConfig.quietHoursStart *= -1;
app.saveConfig("quietHoursStart");
else if (!isChecked && app.config.getSync().getQuietHoursStart() > 0) {
app.config.getSync().setQuietHoursStart(app.config.getSync().getQuietHoursStart() * -1);
}
else if (isChecked && app.appConfig.quietHoursStart == 0) {
app.appConfig.quietHoursStart = new Time(22, 30, 0).getInMillis();
app.appConfig.quietHoursEnd = new Time(5, 30, 0).getInMillis();
else if (isChecked && app.config.getSync().getQuietHoursStart() == 0) {
app.config.getSync().setQuietHoursStart(new Time(22, 30, 0).getInMillis());
app.config.getSync().setQuietHoursEnd(new Time(5, 30, 0).getInMillis());
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
refreshMaterialAboutList();
app.saveConfig("quietHoursStart", "quietHoursEnd");
}
return true;
});
@ -727,10 +714,9 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.appConfig.notifyAboutUpdates)
.setChecked(app.config.getSync().getNotifyAboutUpdates())
.setOnChangeAction((isChecked, tag) -> {
app.appConfig.notifyAboutUpdates = isChecked;
app.saveConfig("notifyAboutUpdates");
app.config.getSync().setNotifyAboutUpdates(isChecked);
return true;
})
);
@ -809,11 +795,11 @@ public class SettingsNewFragment extends MaterialAboutFragment {
}
}
private String getRegisterCardBellSyncSubText() {
if (app.appConfig.bellSyncDiff == null)
if (app.config.getTimetable().getBellSyncDiff() == null)
return getString(R.string.settings_register_bell_sync_subtext_disabled);
return getString(
R.string.settings_register_bell_sync_subtext_format,
(app.appConfig.bellSyncMultiplier == -1 ? "-" : "+") + app.appConfig.bellSyncDiff.getStringHMS()
(app.config.getTimetable().getBellSyncMultiplier() == -1 ? "-" : "+") + app.config.getTimetable().getBellSyncDiff().getStringHMS()
);
}
private MaterialAboutItem getRegisterCardSharedEventsItem() {
@ -972,8 +958,8 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.neutralText(R.string.reset)
.inputRangeRes(8, 8, R.color.md_red_500)
.input("±H:MM:SS",
(app.appConfig.bellSyncDiff != null
? (app.appConfig.bellSyncMultiplier == -1 ? "-" : "+") + app.appConfig.bellSyncDiff.getStringHMS()
(app.config.getTimetable().getBellSyncDiff() != null
? (app.config.getTimetable().getBellSyncMultiplier() == -1 ? "-" : "+") + app.config.getTimetable().getBellSyncDiff().getStringHMS()
: ""), (dialog, input) -> {
if (input == null)
return;
@ -986,10 +972,10 @@ public class SettingsNewFragment extends MaterialAboutFragment {
return;
}
if (input.charAt(0) == '+') {
app.appConfig.bellSyncMultiplier = 1;
app.config.getTimetable().setBellSyncMultiplier(1);
}
else if (input.charAt(0) == '-') {
app.appConfig.bellSyncMultiplier = -1;
app.config.getTimetable().setBellSyncMultiplier(-1);
}
else {
Toast.makeText(activity, R.string.bell_sync_adjust_error, Toast.LENGTH_SHORT).show();
@ -1010,15 +996,13 @@ public class SettingsNewFragment extends MaterialAboutFragment {
return;
}
app.appConfig.bellSyncDiff = new Time(hour, minute, second);
app.saveConfig("bellSyncDiff", "bellSyncMultiplier");
app.config.getTimetable().setBellSyncDiff(new Time(hour, minute, second));
registerCardBellSyncItem.setSubText(getRegisterCardBellSyncSubText());
refreshMaterialAboutList();
})
.onNeutral(((dialog, which) -> {
app.appConfig.bellSyncDiff = null;
app.appConfig.bellSyncMultiplier = 0;
app.saveConfig("bellSyncDiff", "bellSyncMultiplier");
app.config.getTimetable().setBellSyncDiff(null);
app.config.getTimetable().setBellSyncMultiplier(0);
registerCardBellSyncItem.setSubText(getRegisterCardBellSyncSubText());
refreshMaterialAboutList();
}))
@ -1035,9 +1019,9 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.appConfig.dontCountZeroToAverage)
.setChecked(!app.config.getFor(app.profileId).getGrades().getCountZeroToAvg())
.setOnChangeAction((isChecked, tag) -> {
app.appConfig.dontCountZeroToAverage = isChecked;
app.config.getFor(app.profileId).getGrades().setCountZeroToAvg(!isChecked);
app.saveConfig("dontCountZeroToAverage");
return true;
})
@ -1052,10 +1036,9 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.appConfig.countInSeconds)
.setChecked(app.config.getTimetable().getCountInSeconds())
.setOnChangeAction((isChecked, tag) -> {
app.appConfig.countInSeconds = isChecked;
app.saveConfig("countInSeconds");
app.config.getTimetable().setCountInSeconds(isChecked);
return true;
})
);
@ -1166,17 +1149,17 @@ public class SettingsNewFragment extends MaterialAboutFragment {
.title(getString(R.string.settings_about_language_dialog_title))
.content(getString(R.string.settings_about_language_dialog_text))
.items(getString(R.string.language_system), getString(R.string.language_polish), getString(R.string.language_english))
.itemsCallbackSingleChoice(app.appConfig.language == null ? 0 : app.appConfig.language.equals("pl") ? 1 : 2, (dialog, itemView, which, text) -> {
.itemsCallbackSingleChoice(app.config.getUi().getLanguage() == null ? 0 : app.config.getUi().getLanguage().equals("pl") ? 1 : 2, (dialog, itemView, which, text) -> {
switch (which) {
case 0:
app.appConfig.language = null;
app.config.getUi().setLanguage(null);
initDefaultLocale();
break;
case 1:
app.appConfig.language = "pl";
app.config.getUi().setLanguage("pl");
break;
case 2:
app.appConfig.language = "en";
app.config.getUi().setLanguage("en");
break;
}
app.saveConfig("language");
@ -1397,10 +1380,9 @@ public class SettingsNewFragment extends MaterialAboutFragment {
else if (requestCode == 22 && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
app.appConfig.headerBackground = getRealPathFromURI(getContext(), uri);
app.saveConfig("headerBackground");
app.config.getUi().setHeaderBackground(getRealPathFromURI(getContext(), uri));
if (activity != null) {
activity.getDrawer().setAccountHeaderBackground(app.appConfig.headerBackground);
activity.getDrawer().setAccountHeaderBackground(app.config.getUi().getHeaderBackground());
activity.getDrawer().open();
}
}
@ -1408,8 +1390,7 @@ public class SettingsNewFragment extends MaterialAboutFragment {
else if (requestCode == 23 && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
app.appConfig.appBackground = getRealPathFromURI(getContext(), uri);
app.saveConfig("appBackground");
app.config.getUi().setAppBackground(getRealPathFromURI(getContext(), uri));
if (activity != null) {
activity.recreate();
}

View File

@ -149,10 +149,10 @@ public class TimetableFragment extends Fragment {
Date today = Date.getToday();
Date date = Date.getToday();
int weekBeginning = app.appConfig.timetableDisplayDaysBackward - date.getWeekDay();
int weekBeginning = 2 - date.getWeekDay();
int weekEnd = weekBeginning + 6;
date.stepForward(0, 0, 0 - (app.appConfig.timetableDisplayDaysBackward));
for (int i = 0; i < app.appConfig.timetableDisplayDaysForward + app.appConfig.timetableDisplayDaysBackward + 1; i++) {
date.stepForward(0, 0, 0 - (2));
for (int i = 0; i < 7 + 2 + 1; i++) {
Bundle args = new Bundle();
args.putLong("date", date.getValue());
TimetableDayFragment timetableDayFragment = new TimetableDayFragment();
@ -176,7 +176,7 @@ public class TimetableFragment extends Fragment {
Log.d(TAG, "Got date "+getArguments().getLong("timetableDate", 0));
pageSelection = app.appConfig.timetableDisplayDaysBackward + Date.diffDays(gotDate, today);
pageSelection = 2 + Date.diffDays(gotDate, today);
displayingDate = gotDate;
}
else if (pageSelection == -1) {
@ -186,7 +186,7 @@ public class TimetableFragment extends Fragment {
List<LessonFull> lessons = app.db.lessonDao().getAllWeekNow(App.profileId, today.getWeekStart(), today);
displayingDate = HomeFragment.findDateWithLessons(App.profileId, lessons);
pageSelection = app.appConfig.timetableDisplayDaysBackward + Date.diffDays(displayingDate, today); // DEFAULT HERE
pageSelection = 2 + Date.diffDays(displayingDate, today); // DEFAULT HERE
activity.runOnUiThread(() -> {
viewPager.setCurrentItem(pageSelection, false);

View File

@ -1,9 +1,6 @@
package pl.szczodrzynski.edziennik.utils.models;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
@ -11,86 +8,21 @@ import java.util.Map;
import java.util.TreeMap;
import pl.szczodrzynski.edziennik.App;
import pl.szczodrzynski.edziennik.BuildConfig;
import pl.szczodrzynski.edziennik.MainActivity;
import pl.szczodrzynski.edziennik.widgets.WidgetConfig;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_IUCZNIOWIE;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_LIBRUS;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_MOBIDZIENNIK;
import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_VULCAN;
public class AppConfig {
private static final String TAG = "AppConfig";
public int appTheme = 1;
public List<Notification> notifications;
public long lastDeleteUnused = System.currentTimeMillis();
public Map<Long, Boolean> teacherImages = null;
public boolean dontCountZeroToAverage = false;
public AppConfig(App _app) {
notifications = new ArrayList<>();
miniDrawerButtonIds = new ArrayList<>();
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_HOME);
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_TIMETABLE);
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_AGENDA);
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_GRADES);
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_MESSAGES);
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_HOMEWORK);
miniDrawerButtonIds.add(MainActivity.DRAWER_ITEM_SETTINGS);
fcmToken = "";
fcmTokens = new TreeMap<>();
fcmTokens.put(LOGIN_TYPE_MOBIDZIENNIK, new Pair<>("", new ArrayList<>()));
fcmTokens.put(LOGIN_TYPE_LIBRUS, new Pair<>("", new ArrayList<>()));
fcmTokens.put(LOGIN_TYPE_IUCZNIOWIE, new Pair<>("", new ArrayList<>()));
fcmTokens.put(LOGIN_TYPE_VULCAN, new Pair<>("", new ArrayList<>()));
}
public Map<Integer, WidgetConfig> widgetTimetableConfigs = new TreeMap<>();
public static final int ORDER_BY_DATE_DESC = 0;
public static final int ORDER_BY_SUBJECT_ASC = 1;
public static final int ORDER_BY_DATE_ASC = 2;
public static final int ORDER_BY_SUBJECT_DESC = 3;
public int gradesOrderBy = ORDER_BY_DATE_DESC;
public String headerBackground = null;
public String appBackground = null;
public int lastAppVersion = BuildConfig.VERSION_CODE;
public boolean registerSyncEnabled = true;
public boolean registerSyncOnlyWifi = false;
public int registerSyncInterval = 60 * 60; // seconds
public int timetableDisplayDaysForward = 7;
public int timetableDisplayDaysBackward = 2;
//public boolean syncNotificationsEnabled = true;
public String fcmToken;
public Map<Integer, Pair<String, List<Integer>>> fcmTokens;
public boolean miniDrawerVisible = false;
//public boolean autoRegistrationAllowed = false;
public boolean loginFinished = false;
public Time bellSyncDiff = null;
public int bellSyncMultiplier = 0;
public boolean savePending = false;
public List<Integer> miniDrawerButtonIds;
public boolean notifyAboutUpdates = true;
public String updateVersion = "";
public String updateUrl = "";
public String updateFilename = "";
@ -99,25 +31,9 @@ public class AppConfig {
public boolean webPushEnabled = false;
public boolean tapTargetSetAsRead = false;
public boolean tapTargetSwitchProfile = false;
public boolean countInSeconds = false;
public long quietHoursStart = 0;
public long quietHoursEnd = 0;
public boolean quietDuringLessons = true;
public String devModePassword = null;
public long appInstalledTime = 0;
public long appRateSnackbarTime = 0;
public int mobidziennikOldMessages = -1;
@Nullable
public String language = null;
@NonNull
public boolean dontShowAppManagerDialog = false;
}

View File

@ -560,6 +560,7 @@
<string name="opening_file">Otwieranie %s</string>
<string name="opening_file_no_app">Brak aplikacji otwierającej ten typ pliku</string>
<string name="please_wait">Proszę czekać</string>
<string name="preference_file" translatable="false">pl.szczodrzynski.edziennik_preferences</string>
<string name="preference_file_global" translatable="false">pl.szczodrzynski.edziennik_profiles</string>
<string name="preference_file_register" translatable="false">pl.szczodrzynski.edziennik_profile%d_register</string>
<string name="prefix" translatable="false">pl</string>