From 163f56475cc8f8af40f2c8ff18a987dbcfdced40 Mon Sep 17 00:00:00 2001 From: Gideon Okuro Date: Wed, 13 Mar 2024 22:10:47 +0300 Subject: [PATCH] sync: more stability through safe call operators (fixes #3237) (#3238) Co-authored-by: dogi --- app/build.gradle | 4 +- .../myplanet/base/BaseRecyclerFragment.java | 13 +- .../planet/myplanet/callback/SyncListener.kt | 2 +- .../ole/planet/myplanet/model/RealmMeetup.kt | 8 +- .../planet/myplanet/model/RealmMyCourse.kt | 9 +- .../planet/myplanet/model/RealmMyLibrary.kt | 16 +- .../planet/myplanet/model/RealmRemovedLog.kt | 14 +- .../planet/myplanet/model/RealmSubmission.kt | 6 +- .../myplanet/service/AudioRecorderService.kt | 12 +- .../planet/myplanet/service/AutoSyncWorker.kt | 10 +- .../planet/myplanet/service/SyncManager.kt | 24 +- .../planet/myplanet/service/UploadManager.kt | 441 ++++++------------ .../myplanet/service/UploadToShelfService.kt | 199 +++----- .../myplanet/service/UserProfileDbHandler.kt | 12 +- .../ui/dashboard/BaseDashboardFragment.kt | 2 +- .../ui/library/AddResourceFragment.kt | 8 +- .../planet/myplanet/ui/sync/SyncActivity.kt | 4 +- .../myplanet/ui/viewer/PDFReaderActivity.kt | 6 +- .../planet/myplanet/utilities/FileUtils.kt | 4 +- .../planet/myplanet/utilities/Utilities.kt | 10 +- 20 files changed, 307 insertions(+), 497 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 9cd26f0c96..655bc12c8c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -9,8 +9,8 @@ android { applicationId "org.ole.planet.myplanet" minSdkVersion 21 targetSdkVersion 34 - versionCode 1411 - versionName "0.14.11" + versionCode 1412 + versionName "0.14.12" ndkVersion '21.3.6528147' testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true diff --git a/app/src/main/java/org/ole/planet/myplanet/base/BaseRecyclerFragment.java b/app/src/main/java/org/ole/planet/myplanet/base/BaseRecyclerFragment.java index ce05fc38dd..061f5d11a6 100644 --- a/app/src/main/java/org/ole/planet/myplanet/base/BaseRecyclerFragment.java +++ b/app/src/main/java/org/ole/planet/myplanet/base/BaseRecyclerFragment.java @@ -33,6 +33,7 @@ import io.realm.Case; import io.realm.RealmList; import io.realm.RealmObject; +import io.realm.RealmResults; import static android.content.Context.MODE_PRIVATE; @@ -209,13 +210,15 @@ public List filterLibraryByTag(String s, List tags) { } public List filterCourseByTag(String s, List tags) { - if (tags.size() == 0 && s.isEmpty()) { + if (tags.isEmpty() && s.isEmpty()) { return applyCourseFilter((List) getList(RealmMyCourse.class)); } - List list = (List) getData(s, RealmMyCourse.class); - if (isMyCourseLib) list = RealmMyCourse.getMyCourseByUserId(model.id, list); - else list = RealmMyCourse.getOurCourse(model.id, list); - if (tags.size() == 0) return list; + RealmResults list = (RealmResults) getData(s, RealmMyCourse.class); + if (isMyCourseLib) { + list = (RealmResults) RealmMyCourse.getMyCourseByUserId(model.id, list); + } + else list = (RealmResults) RealmMyCourse.getOurCourse(model.id, list); + if (tags.isEmpty()) return list; RealmList courses = new RealmList<>(); for (RealmMyCourse course : list) { checkAndAddToList(course, courses, tags); diff --git a/app/src/main/java/org/ole/planet/myplanet/callback/SyncListener.kt b/app/src/main/java/org/ole/planet/myplanet/callback/SyncListener.kt index ab7bccc46e..61920fc713 100644 --- a/app/src/main/java/org/ole/planet/myplanet/callback/SyncListener.kt +++ b/app/src/main/java/org/ole/planet/myplanet/callback/SyncListener.kt @@ -6,5 +6,5 @@ interface SyncListener { @JvmSuppressWildcards fun onSyncComplete() @JvmSuppressWildcards - fun onSyncFailed(msg: String) + fun onSyncFailed(msg: String?) } diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMeetup.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMeetup.kt index 2f69b53cc1..30c7d2ee38 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMeetup.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMeetup.kt @@ -81,11 +81,11 @@ open class RealmMeetup : RealmObject() { @JvmStatic fun insertMyMeetups() {} @JvmStatic - fun getMyMeetUpIds(realm: Realm, userId: String?): JsonArray { - val meetups = realm.where(RealmMeetup::class.java).isNotEmpty("userId") - .equalTo("userId", userId, Case.INSENSITIVE).findAll() + fun getMyMeetUpIds(realm: Realm?, userId: String?): JsonArray { + val meetups = realm?.where(RealmMeetup::class.java)?.isNotEmpty("userId") + ?.equalTo("userId", userId, Case.INSENSITIVE)?.findAll() val ids = JsonArray() - for (lib in meetups) { + for (lib in meetups ?: emptyList()) { ids.add(lib.meetupId) } return ids diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt index d5c6b77134..5ba40a32ba 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt @@ -8,6 +8,7 @@ import com.google.gson.JsonObject import io.realm.Realm import io.realm.RealmList import io.realm.RealmObject +import io.realm.RealmResults import io.realm.annotations.PrimaryKey import org.ole.planet.myplanet.MainApplication import org.ole.planet.myplanet.utilities.JsonUtils @@ -114,9 +115,9 @@ open class RealmMyCourse : RealmObject() { } @JvmStatic - fun getMyCourseByUserId(userId: String?, libs: List): List { + fun getMyCourseByUserId(userId: String?, libs: RealmResults?): List { val libraries: MutableList = ArrayList() - for (item in libs) { + for (item in libs ?: emptyList()) { if (item.userId!!.contains(userId)) { libraries.add(item) } @@ -163,8 +164,8 @@ open class RealmMyCourse : RealmObject() { } @JvmStatic - fun getMyCourseIds(realm: Realm, userId: String?): JsonArray { - val myCourses = getMyCourseByUserId(userId, realm.where(RealmMyCourse::class.java).findAll()) + fun getMyCourseIds(realm: Realm?, userId: String?): JsonArray { + val myCourses = getMyCourseByUserId(userId, realm?.where(RealmMyCourse::class.java)?.findAll()) val ids = JsonArray() for (lib in myCourses) { ids.add(lib.courseId) diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt index 3e0dd00c19..02720b043c 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt @@ -305,14 +305,14 @@ open class RealmMyLibrary : RealmObject() { } @JvmStatic - fun serialize(personal: RealmMyLibrary, user: RealmUserModel): JsonObject { + fun serialize(personal: RealmMyLibrary, user: RealmUserModel?): JsonObject { val `object` = JsonObject() `object`.addProperty("title", personal.title) `object`.addProperty("uploadDate", Date().time) `object`.addProperty("createdDate", personal.createdDate) `object`.addProperty("filename", FileUtils.getFileNameFromUrl(personal.resourceLocalAddress)) - `object`.addProperty("author", user.name) - `object`.addProperty("addedBy", user.id) + `object`.addProperty("author", user?.name) + `object`.addProperty("addedBy", user?.id) `object`.addProperty("medium", personal.medium) `object`.addProperty("description", personal.description) `object`.addProperty("year", personal.year) @@ -324,8 +324,8 @@ open class RealmMyLibrary : RealmObject() { `object`.add("resourceFor", JsonUtils.getAsJsonArray(personal.resourceFor)) `object`.addProperty("private", false) `object`.addProperty("isDownloadable", "") - `object`.addProperty("sourcePlanet", user.planetCode) - `object`.addProperty("resideOn", user.planetCode) + `object`.addProperty("sourcePlanet", user?.planetCode) + `object`.addProperty("resideOn", user?.planetCode) `object`.addProperty("updatedDate", Calendar.getInstance().timeInMillis) `object`.addProperty("createdDate", personal.createdDate) `object`.addProperty("androidId", NetworkUtils.getUniqueIdentifier()) @@ -449,10 +449,10 @@ open class RealmMyLibrary : RealmObject() { } @JvmStatic - fun getMyLibIds(realm: Realm, userId: String?): JsonArray { - val myLibraries: List = realm.where(RealmMyLibrary::class.java).contains("userId", userId).findAll() + fun getMyLibIds(realm: Realm?, userId: String?): JsonArray { + val myLibraries: RealmResults? = realm?.where(RealmMyLibrary::class.java)?.contains("userId", userId)?.findAll() val ids = JsonArray() - for (lib in myLibraries) { + for (lib in myLibraries ?: emptyList()) { ids.add(lib.id) } return ids diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmRemovedLog.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmRemovedLog.kt index 392a6acfe9..6365f08cd1 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmRemovedLog.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmRemovedLog.kt @@ -35,18 +35,16 @@ open class RealmRemovedLog : RealmObject() { } @JvmStatic - fun removedIds(realm: Realm, type: String, userId: String): Array { - val removedLibs = realm.where(RealmRemovedLog::class.java) - .equalTo("userId", userId) - .equalTo("type", type) - .findAll() + fun removedIds(realm: Realm?, type: String, userId: String?): Array { + val removedLibs = realm?.where(RealmRemovedLog::class.java) + ?.equalTo("userId", userId) + ?.equalTo("type", type) + ?.findAll() if (removedLibs != null) { val ids = Array(removedLibs.size) { "" } - var i = 0 - for (removed in removedLibs) { + for ((i, removed) in removedLibs.withIndex()) { ids[i] = removed.docId ?: "" - i++ } return ids } diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmSubmission.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmSubmission.kt index 9c97a82ce8..bd7ba83e32 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmSubmission.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmSubmission.kt @@ -170,13 +170,13 @@ open class RealmSubmission : RealmObject() { @JvmStatic @Throws(IOException::class) - fun continueResultUpload(sub: RealmSubmission, apiInterface: ApiInterface, realm: Realm, context: Context?) { + fun continueResultUpload(sub: RealmSubmission, apiInterface: ApiInterface?, realm: Realm, context: Context?) { var `object`: JsonObject? = null if (!TextUtils.isEmpty(sub.userId) && sub.userId!!.startsWith("guest")) return `object` = if (TextUtils.isEmpty(sub._id)) { - apiInterface.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/submissions", serializeExamResult(realm, sub, context)).execute().body() + apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/submissions", serializeExamResult(realm, sub, context))?.execute()?.body() } else { - apiInterface.putDoc(Utilities.header, "application/json", Utilities.getUrl() + "/submissions/" + sub._id, serializeExamResult(realm, sub, context)).execute().body() + apiInterface?.putDoc(Utilities.header, "application/json", Utilities.getUrl() + "/submissions/" + sub._id, serializeExamResult(realm, sub, context))?.execute()?.body() } if (`object` != null) { sub._id = JsonUtils.getString("id", `object`) diff --git a/app/src/main/java/org/ole/planet/myplanet/service/AudioRecorderService.kt b/app/src/main/java/org/ole/planet/myplanet/service/AudioRecorderService.kt index 15d76573e1..6be742570a 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/AudioRecorderService.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/AudioRecorderService.kt @@ -40,7 +40,7 @@ class AudioRecorderService { audioRecordListener?.onRecordStarted() } catch (e: Exception) { myAudioRecorder = null - audioRecordListener?.onError(e.message!!) + audioRecordListener?.onError(e.message) } } } @@ -81,16 +81,16 @@ class AudioRecorderService { fun stopRecording() { if (myAudioRecorder != null) { - myAudioRecorder!!.stop() - myAudioRecorder!!.release() + myAudioRecorder?.stop() + myAudioRecorder?.release() myAudioRecorder = null - audioRecordListener?.onRecordStopped(outputFile!!) + audioRecordListener?.onRecordStopped(outputFile) } } interface AudioRecordListener { fun onRecordStarted() - fun onRecordStopped(outputFile: String) - fun onError(error: String) + fun onRecordStopped(outputFile: String?) + fun onError(error: String?) } } \ No newline at end of file diff --git a/app/src/main/java/org/ole/planet/myplanet/service/AutoSyncWorker.kt b/app/src/main/java/org/ole/planet/myplanet/service/AutoSyncWorker.kt index c2f1089464..010df9742b 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/AutoSyncWorker.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/AutoSyncWorker.kt @@ -59,8 +59,8 @@ class AutoSyncWorker(private val context: Context, workerParams: WorkerParameter override fun onReceive(context: Context, intent: Intent) { if (intent.action == DashboardActivity.MESSAGE_PROGRESS) { val download = intent.getParcelableExtra("download") - if (!download!!.failed && download.completeAll) { - installApk(context, download.fileUrl!!) + if (!download?.failed!! && download.completeAll) { + installApk(context, download.fileUrl) } } } @@ -74,7 +74,7 @@ class AutoSyncWorker(private val context: Context, workerParams: WorkerParameter Utilities.log("Sync completed") } - override fun onSyncFailed(msg: String) { + override fun onSyncFailed(msg: String?) { if (MainApplication.syncFailedCount > 3) { context.startActivity(Intent(context, LoginActivity::class.java) .putExtra("showWifiDialog", true) @@ -84,7 +84,7 @@ class AutoSyncWorker(private val context: Context, workerParams: WorkerParameter override fun onUpdateAvailable(info: MyPlanet, cancelable: Boolean) { if (Constants.showBetaFeature(Constants.KEY_AUTOUPDATE, context)) { - startDownloadUpdate(context, Utilities.getApkUpdateUrl(info.localapkpath!!), null) + startDownloadUpdate(context, Utilities.getApkUpdateUrl(info.localapkpath), null) } } @@ -94,7 +94,7 @@ class AutoSyncWorker(private val context: Context, workerParams: WorkerParameter SyncManager.instance?.start(this) UploadToShelfService.instance?.uploadUserData { Service(MainApplication.context).healthAccess { - UploadToShelfService.instance!!.uploadHealth() + UploadToShelfService.instance?.uploadHealth() } } if (!MainApplication.isSyncRunning) { diff --git a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt index 8d6ebd4e8b..7b97f414c7 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt @@ -61,11 +61,11 @@ class SyncManager private constructor(private val context: Context) { ourInstance = null settings.edit().putLong("LastSync", Date().time).apply() if (listener != null) { - listener!!.onSyncComplete() + listener?.onSyncComplete() } try { mRealm.close() - td!!.stop() + td?.stop() } catch (e: Exception) { e.printStackTrace() } @@ -80,7 +80,7 @@ class SyncManager private constructor(private val context: Context) { destroy() } } - td!!.start() + td?.start() } private fun startSync() { @@ -112,7 +112,7 @@ class SyncManager private constructor(private val context: Context) { TransactionSyncManager.syncDb(mRealm, "certifications") TransactionSyncManager.syncDb(mRealm, "team_activities") TransactionSyncManager.syncDb(mRealm, "chat_history") - ManagerSync.instance!!.syncAdmin() + ManagerSync.instance?.syncAdmin() resourceTransactionSync(listener) onSynced(mRealm, settings) mRealm.close() @@ -128,12 +128,12 @@ class SyncManager private constructor(private val context: Context) { if (listener != null) { isSyncing = false MainApplication.syncFailedCount++ - listener!!.onSyncFailed(message!!) + listener?.onSyncFailed(message) } } fun resourceTransactionSync(listener: SyncListener?) { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm.executeTransaction { try { syncResource(apiInterface, listener) @@ -144,11 +144,11 @@ class SyncManager private constructor(private val context: Context) { } @Throws(IOException::class) - private fun syncResource(dbClient: ApiInterface, listener: SyncListener?) { + private fun syncResource(dbClient: ApiInterface?, listener: SyncListener?) { val newIds: MutableList = ArrayList() - val allDocs = dbClient.getJsonObject(Utilities.header, Utilities.getUrl() + "/resources/_all_docs?include_doc=false") - val all = allDocs.execute() - val rows = getJsonArray("rows", all.body()) + val allDocs = dbClient?.getJsonObject(Utilities.header, Utilities.getUrl() + "/resources/_all_docs?include_doc=false") + val all = allDocs?.execute() + val rows = getJsonArray("rows", all?.body()) val keys: MutableList = ArrayList() for (i in 0 until rows.size()) { val `object` = rows[i].asJsonObject @@ -156,8 +156,8 @@ class SyncManager private constructor(private val context: Context) { if (i == rows.size() - 1 || keys.size == 1000) { val obj = JsonObject() obj.add("keys", Gson().fromJson(Gson().toJson(keys), JsonArray::class.java)) - val response = dbClient.findDocs(Utilities.header, "application/json", Utilities.getUrl() + "/resources/_all_docs?include_docs=true", obj).execute() - if (response.body() != null) { + val response = dbClient?.findDocs(Utilities.header, "application/json", Utilities.getUrl() + "/resources/_all_docs?include_docs=true", obj)?.execute() + if (response?.body() != null) { val ids: List = save(getJsonArray("rows", response.body()), mRealm) newIds.addAll(ids) } diff --git a/app/src/main/java/org/ole/planet/myplanet/service/UploadManager.kt b/app/src/main/java/org/ole/planet/myplanet/service/UploadManager.kt index 65570c18a0..6099a69a4b 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/UploadManager.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/UploadManager.kt @@ -74,7 +74,7 @@ class UploadManager(context: Context) : FileUploadService() { var context: Context var pref: SharedPreferences private val dbService: DatabaseService - private var mRealm: Realm? = null + lateinit var mRealm: Realm init { dbService = DatabaseService(context) @@ -83,13 +83,13 @@ class UploadManager(context: Context) : FileUploadService() { } private fun uploadNewsActivities() { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync { realm: Realm -> + mRealm.executeTransactionAsync { realm: Realm -> val newsLog: List = realm.where(RealmNewsLog::class.java).isNull("_id").or().isEmpty("_id").findAll() for (news in newsLog) { try { - val `object` = apiInterface.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/myplanet_activities", serialize(news)).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/myplanet_activities", serialize(news))?.execute()?.body() Utilities.log("Team upload " + Gson().toJson(`object`)) if (`object` != null) { news._id = getString("id", `object`) @@ -103,23 +103,15 @@ class UploadManager(context: Context) : FileUploadService() { } fun uploadActivities(listener: SuccessListener?) { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) val model = UserProfileDbHandler(MainApplication.context).userModel ?: return if (model.isManager()) return try { - apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/myplanet_activities", - getNormalMyPlanetActivities(MainApplication.context, pref, model) - ).enqueue(object : Callback { + apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/myplanet_activities", getNormalMyPlanetActivities(MainApplication.context, pref, model))?.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) {} override fun onFailure(call: Call, t: Throwable) {} }) - apiInterface.getJsonObject( - Utilities.header, - Utilities.getUrl() + "/myplanet_activities/" + getAndroidId(MainApplication.context) + "@" + getUniqueIdentifier() - ).enqueue(object : Callback { + apiInterface?.getJsonObject(Utilities.header, Utilities.getUrl() + "/myplanet_activities/" + getAndroidId(MainApplication.context) + "@" + getUniqueIdentifier())?.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { var `object` = response.body() if (`object` != null) { @@ -129,16 +121,8 @@ class UploadManager(context: Context) : FileUploadService() { } else { `object` = getMyPlanetActivities(context, pref, model) } - apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/myplanet_activities", - `object` - ).enqueue(object : Callback { - override fun onResponse( - call: Call, - response: Response - ) { + apiInterface.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/myplanet_activities", `object`).enqueue(object : Callback { + override fun onResponse(call: Call, response: Response) { listener?.onSuccess("My planet activities uploaded successfully") } @@ -155,15 +139,15 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadExamResult(listener: SuccessListener) { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync( + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync( { realm: Realm -> val submissions: List = realm.where( RealmSubmission::class.java ).findAll() for (sub in submissions) { try { - if (sub.answers!!.size > 0) { + if ((sub.answers?.size ?: 0) > 0) { continueResultUpload(sub, apiInterface, realm, context) } } catch (e: Exception) { @@ -195,27 +179,17 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadAchievement() { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> - val list: List = realm.where( - RealmAchievement::class.java - ).findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> + val list: List = realm.where(RealmAchievement::class.java).findAll() for (sub in list) { try { - if (sub.get_id()!!.startsWith("guest")) continue - val ob = apiInterface.putDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/achievements/" + sub.get_id(), - serialize(sub) - ).execute().body() + if (sub.get_id()?.startsWith("guest") == true) { + continue + } + val ob = apiInterface?.putDoc(Utilities.header, "application/json", Utilities.getUrl() + "/achievements/" + sub.get_id(), serialize(sub))?.execute()?.body() if (ob == null) { - val re = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/achievements", - serialize(sub) - ).execute().errorBody() + val re = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/achievements", serialize(sub))?.execute()?.errorBody() } } catch (e: IOException) { e.printStackTrace() @@ -225,21 +199,16 @@ class UploadManager(context: Context) : FileUploadService() { } fun uploadCourseProgress() { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync { realm: Realm -> - val data: List = realm.where( - RealmCourseProgress::class.java - ).isNull("_id").findAll() + mRealm.executeTransactionAsync { realm: Realm -> + val data: List = realm.where(RealmCourseProgress::class.java).isNull("_id").findAll() for (sub in data) { try { - if (sub.userId!!.startsWith("guest")) continue - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/courses_progress", - serializeProgress(sub) - ).execute().body() + if (sub.userId?.startsWith("guest") == true) { + continue + } + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/courses_progress", serializeProgress(sub))?.execute()?.body() if (`object` != null) { sub.set_id(getString("id", `object`)) sub.set_rev(getString("rev", `object`)) @@ -252,61 +221,41 @@ class UploadManager(context: Context) : FileUploadService() { } fun uploadFeedback(listener: SuccessListener) { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync( - Realm.Transaction { realm: Realm -> - val feedbacks: List = realm.where( - RealmFeedback::class.java - ).findAll() - for (feedback in feedbacks) { - try { - var res: Response<*> - res = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/feedback", - serializeFeedback(feedback) - ).execute() - val r = res.body() - if (r != null) { - val revElement = r["rev"] - val idElement = r["id"] - if (revElement != null && idElement != null) { - feedback.set_rev(revElement.asString) - feedback.set_id(idElement.asString) - } else { - Utilities.log("Missing 'rev' or 'id' elements in the JSON response") - } + mRealm.executeTransactionAsync(Realm.Transaction { realm: Realm -> + val feedbacks: List = realm.where(RealmFeedback::class.java).findAll() + for (feedback in feedbacks) { + try { + val res: Response? = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/feedback", serializeFeedback(feedback))?.execute() + val r = res?.body() + if (r != null) { + val revElement = r["rev"] + val idElement = r["id"] + if (revElement != null && idElement != null) { + feedback.set_rev(revElement.asString) + feedback.set_id(idElement.asString) } else { - Utilities.log( - "ERRRRRRRR " + res.errorBody()!! - .string() - ) + Utilities.log("Missing 'rev' or 'id' elements in the JSON response") } - } catch (e: IOException) { - e.printStackTrace() + } else { + Utilities.log("ERRRRRRRR " + res?.errorBody()?.string()) } + } catch (e: IOException) { + e.printStackTrace() } - }, + } }, Realm.Transaction.OnSuccess { listener.onSuccess("Feedback sync completed successfully") }) } fun uploadSubmitPhotos(listener: SuccessListener?) { mRealm = DatabaseService(context).realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> - val data: List = realm.where( - RealmSubmitPhotos::class.java - ).equalTo("uploaded", false).findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> + val data: List = realm.where(RealmSubmitPhotos::class.java).equalTo("uploaded", false).findAll() for (sub in data) { try { - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/submissions", - serializeRealmSubmitPhotos(sub) - ).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/submissions", serializeRealmSubmitPhotos(sub))?.execute()?.body() if (`object` != null) { val _rev = getString("rev", `object`) val _id = getString("id", `object`) @@ -325,22 +274,13 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadResource(listener: SuccessListener?) { mRealm = DatabaseService(context).realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> - val user = realm.where( - RealmUserModel::class.java - ).equalTo("id", pref.getString("userId", "")).findFirst() - val data: List = realm.where( - RealmMyLibrary::class.java - ).isNull("_rev").findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> + val user = realm.where(RealmUserModel::class.java).equalTo("id", pref.getString("userId", "")).findFirst() + val data: List = realm.where(RealmMyLibrary::class.java).isNull("_rev").findAll() for (sub in data) { try { - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/resources", - serialize(sub, user!!) - ).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/resources", serialize(sub, user))?.execute()?.body() if (`object` != null) { val _rev = getString("rev", `object`) val _id = getString("id", `object`) @@ -358,24 +298,21 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadMyPersonal(personal: RealmMyPersonal, listener: SuccessListener) { mRealm = DatabaseService(context).realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) if (!personal.isUploaded) { - apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/resources", - serialize(personal, context) - ).enqueue(object : Callback { + apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/resources", serialize(personal, context))?.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { val `object` = response.body() if (`object` != null) { - if (!mRealm!!.isInTransaction) mRealm!!.beginTransaction() + if (!mRealm.isInTransaction) { + mRealm.beginTransaction() + } val _rev = getString("rev", `object`) val _id = getString("id", `object`) personal.isUploaded = true personal.set_rev(_rev) personal.set_id(_id) - mRealm!!.commitTransaction() + mRealm.commitTransaction() uploadAttachment(_id, _rev, personal, listener) } } @@ -389,21 +326,14 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadTeamTask() { mRealm = DatabaseService(context).realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> - val list: List = realm.where( - RealmTeamTask::class.java - ).findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> + val list: List = realm.where(RealmTeamTask::class.java).findAll() for (task in list) { if (TextUtils.isEmpty(task._id) || task.isUpdated) { - var `object`: JsonObject? = null + var `object`: JsonObject? try { - `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/tasks", - serialize(realm, task) - ).execute().body() + `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/tasks", serialize(realm, task))?.execute()?.body() if (`object` != null) { val _rev = getString("rev", `object`) val _id = getString("id", `object`) @@ -419,19 +349,14 @@ class UploadManager(context: Context) : FileUploadService() { } fun uploadTeams() { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync { realm: Realm -> + mRealm.executeTransactionAsync { realm: Realm -> val teams: List = realm.where(RealmMyTeam::class.java).equalTo("updated", true).findAll() Utilities.log("Teams size " + teams.size) for (team in teams) { try { - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/teams", - serialize(team) - ).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/teams", serialize(team))?.execute()?.body() Utilities.log("Team upload " + Gson().toJson(`object`)) if (`object` != null) { team._rev = getString("rev", `object`) @@ -445,48 +370,36 @@ class UploadManager(context: Context) : FileUploadService() { } fun uploadUserActivities(listener: SuccessListener) { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance val model = UserProfileDbHandler(MainApplication.context).userModel ?: return - if (model.isManager()) return - mRealm!!.executeTransactionAsync( - { realm: Realm -> - val activities = realm.where( - RealmOfflineActivity::class.java - ).isNull("_rev").equalTo("type", "login").findAll() - for (act in activities) { - try { - if (act.userId!!.startsWith("guest")) continue - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/login_activities", - serializeLoginActivities(act, context) - ).execute().body() - act.changeRev(`object`) - } catch (e: IOException) { - e.printStackTrace() + if (model.isManager()) { + return + } + mRealm.executeTransactionAsync({ realm: Realm -> + val activities = realm.where(RealmOfflineActivity::class.java).isNull("_rev").equalTo("type", "login").findAll() + for (act in activities) { + try { + if (act.userId?.startsWith("guest") == true) { + continue } + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/login_activities", serializeLoginActivities(act, context))?.execute()?.body() + act.changeRev(`object`) + } catch (e: IOException) { + e.printStackTrace() } - uploadTeamActivities(realm, apiInterface) - }, + } + uploadTeamActivities(realm, apiInterface) }, { listener.onSuccess("Sync with server completed successfully") }) { e: Throwable -> - listener.onSuccess( - e.message - ) + listener.onSuccess(e.message) } } - private fun uploadTeamActivities(realm: Realm, apiInterface: ApiInterface) { + private fun uploadTeamActivities(realm: Realm, apiInterface: ApiInterface?) { val logs = realm.where(RealmTeamLog::class.java).isNull("_rev").findAll() for (log in logs) { try { - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/team_activities", - serializeTeamActivities(log, context) - ).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/team_activities", serializeTeamActivities(log, context))?.execute()?.body() if (`object` != null) { log._id = getString("id", `object`) log._rev = getString("rev", `object`) @@ -500,31 +413,21 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadRating(listener: SuccessListener?) { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> - val activities = realm.where( - RealmRating::class.java - ).equalTo("isUpdated", true).findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> + val activities = realm.where(RealmRating::class.java).equalTo("isUpdated", true).findAll() for (act in activities) { try { - if (act.userId!!.startsWith("guest")) continue - var `object`: Response - `object` = if (TextUtils.isEmpty(act._id)) { - apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/ratings", - serializeRating(act) - ).execute() - } else { - apiInterface.putDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/ratings/" + act._id, - serializeRating(act) - ).execute() + if (act.userId?.startsWith("guest") == true) { + continue + } + val `object`: Response? = + if (TextUtils.isEmpty(act._id)) { + apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/ratings", serializeRating(act))?.execute() + } else { + apiInterface?.putDoc(Utilities.header, "application/json", Utilities.getUrl() + "/ratings/" + act._id, serializeRating(act))?.execute() } - if (`object`.body() != null) { + if (`object`?.body() != null) { act._id = getString("id", `object`.body()) act._rev = getString("rev", `object`.body()) act.isUpdated = false @@ -538,29 +441,23 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadNews() { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) val userModel = UserProfileDbHandler(context).userModel - mRealm!!.executeTransactionAsync { realm: Realm -> - val activities = realm.where( - RealmNews::class.java - ).findAll() + mRealm.executeTransactionAsync { realm: Realm -> + val activities = realm.where(RealmNews::class.java).findAll() for (act in activities) { try { - if (act.userId!!.startsWith("guest")) continue + if (act.userId?.startsWith("guest") == true) { + continue + } val `object` = serializeNews(act) val image = act.imagesArray - val user = realm.where(RealmUserModel::class.java) - .equalTo("id", pref.getString("userId", "")).findFirst() + val user = realm.where(RealmUserModel::class.java).equalTo("id", pref.getString("userId", "")).findFirst() if (act.imageUrls != null) { - for (imageobject in act.imageUrls!!) { + for (imageobject in act.imageUrls ?: emptyList()) { val imgObject = Gson().fromJson(imageobject, JsonObject::class.java) val ob = createImage(user, imgObject) - val response = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/resources", - ob - ).execute().body() + val response = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/resources", ob)?.execute()?.body() val _rev = getString("rev", response) val _id = getString("id", response) val f = File(getString("imageUrl", imgObject)) @@ -569,22 +466,14 @@ class UploadManager(context: Context) : FileUploadService() { val format = "%s/resources/%s/%s" val connection = f.toURL().openConnection() val mimeType = connection.contentType - val body = RequestBody.create( - MediaType.parse("application/octet"), - fullyReadFileToBytes(f) - ) + val body = RequestBody.create(MediaType.parse("application/octet"), fullyReadFileToBytes(f)) val url = String.format(format, Utilities.getUrl(), _id, name) - val res = - apiInterface.uploadResource(getHeaderMap(mimeType, _rev), url, body) - .execute() - val attachment = res.body() + val res = apiInterface?.uploadResource(getHeaderMap(mimeType, _rev), url, body)?.execute() + val attachment = res?.body() val resourceObject = JsonObject() resourceObject.addProperty("resourceId", getString("id", attachment)) resourceObject.addProperty("filename", getString("fileName", imgObject)) - val markdown = "![](resources/" + getString( - "id", - attachment - ) + "/" + getString("fileName", imgObject) + ")" + val markdown = "![](resources/" + getString("id", attachment) + "/" + getString("fileName", imgObject) + ")" resourceObject.addProperty("markdown", markdown) var msg = getString("message", `object`) msg += """ @@ -597,24 +486,14 @@ class UploadManager(context: Context) : FileUploadService() { } act.images = Gson().toJson(image) `object`.add("images", image) - var newsUploadResponse: Response - newsUploadResponse = if (TextUtils.isEmpty(act.get_id())) { - apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/news", - `object` - ).execute() - } else { - apiInterface.putDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/news/" + act.get_id(), - `object` - ).execute() - } - if (newsUploadResponse.body() != null) { - act.imageUrls!!.clear() + val newsUploadResponse: Response? = + if (TextUtils.isEmpty(act.get_id())) { + apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/news", `object`)?.execute() + } else { + apiInterface?.putDoc(Utilities.header, "application/json", Utilities.getUrl() + "/news/" + act.get_id(), `object`)?.execute() + } + if (newsUploadResponse?.body() != null) { + act.imageUrls?.clear() act.set_id(getString("id", newsUploadResponse.body())) act.set_rev(getString("rev", newsUploadResponse.body())) } @@ -628,19 +507,15 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadCrashLog(listener: SuccessListener) { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync(Realm.Transaction { realm: Realm -> - val logs: RealmResults - logs = realm.where(RealmApkLog::class.java).isNull("_rev").findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync(Realm.Transaction { realm: Realm -> + val logs: RealmResults = realm.where(RealmApkLog::class.java).isNull("_rev").findAll() for (act in logs) { try { - val o = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/apk_logs", - serialize(act, context) - ).execute().body() - if (o != null) act.set_rev(getString("rev", o)) + val o = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/apk_logs", serialize(act, context))?.execute()?.body() + if (o != null) { + act.set_rev(getString("rev", o)) + } } catch (e: IOException) { e.printStackTrace() } @@ -650,19 +525,15 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadSearchActivity() { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> - val logs: RealmResults - logs = realm.where(RealmSearchActivity::class.java).isEmpty("_rev").findAll() + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> + val logs: RealmResults = realm.where(RealmSearchActivity::class.java).isEmpty("_rev").findAll() for (act in logs) { try { - val o = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/search_activities", - act.serialize() - ).execute().body() - if (o != null) act._rev = getString("rev", o) + val o = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/search_activities", act.serialize())?.execute()?.body() + if (o != null) { + act._rev = getString("rev", o) + } } catch (e: IOException) { e.printStackTrace() } @@ -672,25 +543,22 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadResourceActivities(type: String) { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - val db = if (type == "sync") "admin_activities" else "resource_activities" - mRealm!!.executeTransactionAsync { realm: Realm -> - val activities: RealmResults - activities = if (type == "sync") { - realm.where(RealmResourceActivity::class.java).isNull("_rev") - .equalTo("type", "sync").findAll() - } else { - realm.where(RealmResourceActivity::class.java).isNull("_rev") - .notEqualTo("type", "sync").findAll() - } + val apiInterface = client?.create(ApiInterface::class.java) + val db = if (type == "sync") { + "admin_activities" + } else { + "resource_activities" + } + mRealm.executeTransactionAsync { realm: Realm -> + val activities: RealmResults = + if (type == "sync") { + realm.where(RealmResourceActivity::class.java).isNull("_rev").equalTo("type", "sync").findAll() + } else { + realm.where(RealmResourceActivity::class.java).isNull("_rev").notEqualTo("type", "sync").findAll() + } for (act in activities) { try { - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/" + db, - serializeResourceActivities(act) - ).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/" + db, serializeResourceActivities(act))?.execute()?.body() if (`object` != null) { act._rev = getString("rev", `object`) act._id = getString("id", `object`) @@ -704,19 +572,14 @@ class UploadManager(context: Context) : FileUploadService() { fun uploadCourseActivities() { mRealm = dbService.realmInstance - val apiInterface = client!!.create(ApiInterface::class.java) - mRealm!!.executeTransactionAsync { realm: Realm -> + val apiInterface = client?.create(ApiInterface::class.java) + mRealm.executeTransactionAsync { realm: Realm -> val activities: RealmResults = realm.where(RealmCourseActivity::class.java).isNull("_rev") .notEqualTo("type", "sync").findAll() for (act in activities) { try { - val `object` = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/course_activities", - serializeSerialize(act) - ).execute().body() + val `object` = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/course_activities", serializeSerialize(act))?.execute()?.body() if (`object` != null) { act.set_rev(getString("rev", `object`)) act.set_id(getString("id", `object`)) diff --git a/app/src/main/java/org/ole/planet/myplanet/service/UploadToShelfService.kt b/app/src/main/java/org/ole/planet/myplanet/service/UploadToShelfService.kt index 5040bdc968..f60b85ace7 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/UploadToShelfService.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/UploadToShelfService.kt @@ -33,78 +33,55 @@ import java.util.Date class UploadToShelfService(context: Context) { private val dbService: DatabaseService private val sharedPreferences: SharedPreferences - private var mRealm: Realm? = null + lateinit var mRealm: Realm init { - sharedPreferences = - context.getSharedPreferences(SyncActivity.PREFS_NAME, Context.MODE_PRIVATE) + sharedPreferences = context.getSharedPreferences(SyncActivity.PREFS_NAME, Context.MODE_PRIVATE) dbService = DatabaseService(context) } fun uploadUserData(listener: SuccessListener) { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync({ realm: Realm -> - val userModels: List = realm.where( - RealmUserModel::class.java - ).isEmpty("_id").or().equalTo("updated", true).findAll() + mRealm.executeTransactionAsync({ realm: Realm -> + val userModels: List = realm.where(RealmUserModel::class.java).isEmpty("_id").or().equalTo("updated", true).findAll() Utilities.log("USER LIST SIZE + " + userModels.size) for (model in userModels) { try { - var res = apiInterface.getJsonObject( - Utilities.header, - Utilities.getUrl() + "/_users/org.couchdb.user:" + model.name - ).execute() - if (res.body() == null) { + var res = apiInterface?.getJsonObject(Utilities.header, Utilities.getUrl() + "/_users/org.couchdb.user:" + model.name)?.execute() + if (res?.body() == null) { val obj = model.serialize() - res = apiInterface.putDoc( - null, - "application/json", - Utilities.getUrl() + "/_users/org.couchdb.user:" + model.name, - obj - ).execute() - if (res.body() != null) { - val id = res.body()!!.get("id").asString - val rev = res.body()!!.get("rev").asString - res = apiInterface.getJsonObject( - Utilities.header, - Utilities.getUrl() + "/_users/" + id - ).execute() - if (res.body() != null) { + res = apiInterface?.putDoc(null, "application/json", Utilities.getUrl() + "/_users/org.couchdb.user:" + model.name, obj)?.execute() + if (res?.body() != null) { + val id = res.body()?.get("id")?.asString + val rev = res.body()?.get("rev")?.asString + res = apiInterface?.getJsonObject(Utilities.header, Utilities.getUrl() + "/_users/" + id)?.execute() + if (res?.body() != null) { model._id = id model._rev = rev model.password_scheme = getString("password_scheme", res.body()) model.derived_key = getString("derived_key", res.body()) model.salt = getString("salt", res.body()) model.iterations = getString("iterations", res.body()) - if (saveKeyIv(apiInterface, model, obj)) updateHealthData( - realm, - model - ) + if (saveKeyIv(apiInterface, model, obj)) { + updateHealthData(realm, model) + } } } } else if (model.isUpdated) { Utilities.log("UPDATED MODEL " + model.serialize()) val obj = model.serialize() - res = apiInterface.putDoc( - null, - "application/json", - Utilities.getUrl() + "/_users/org.couchdb.user:" + model.name, - obj - ).execute() - if (res.body() != null) { - Utilities.log(Gson().toJson(res.body())) - val rev = res.body()!!["rev"].asString + res = apiInterface?.putDoc(null, "application/json", Utilities.getUrl() + "/_users/org.couchdb.user:" + model.name, obj)?.execute() + if (res?.body() != null) { + Utilities.log(Gson().toJson(res?.body())) + val rev = res?.body()!!["rev"].asString model._rev = rev model.isUpdated = false } else { - Utilities.log(res.errorBody()!!.string()) + res?.errorBody()?.let { Utilities.log(it.string()) } } } else { - Utilities.toast( - MainApplication.context, - "User " + model.name + " already exist" - ) + Utilities.toast(MainApplication.context, "User " + model.name + " already exist") } } catch (e: IOException) { e.printStackTrace() @@ -114,38 +91,32 @@ class UploadToShelfService(context: Context) { } private fun updateHealthData(realm: Realm, model: RealmUserModel) { - val list: List = realm.where(RealmMyHealthPojo::class.java - ).equalTo("_id", model.id).findAll() + val list: List = realm.where(RealmMyHealthPojo::class.java).equalTo("_id", model.id).findAll() for (p in list) { p.userId = model._id } } @Throws(IOException::class) - fun saveKeyIv(apiInterface: ApiInterface, model: RealmUserModel, obj: JsonObject): Boolean { - val table = - "userdb-" + Utilities.toHex(model.planetCode!!) + "-" + Utilities.toHex(model.name!!) - val header = "Basic " + Base64.encodeToString( - (obj["name"].asString + ":" + obj["password"].asString).toByteArray(), - Base64.NO_WRAP - ) + fun saveKeyIv(apiInterface: ApiInterface?, model: RealmUserModel, obj: JsonObject): Boolean { + val table = "userdb-" + Utilities.toHex(model.planetCode) + "-" + Utilities.toHex(model.name) + val header = "Basic " + Base64.encodeToString((obj["name"].asString + ":" + obj["password"].asString).toByteArray(), Base64.NO_WRAP) val ob = JsonObject() var keyString = generateKey() var iv: String? = generateIv() - if (!TextUtils.isEmpty(model.iv)) iv = model.iv - if (!TextUtils.isEmpty(model.key)) keyString = model.key + if (!TextUtils.isEmpty(model.iv)) { + iv = model.iv + } + if (!TextUtils.isEmpty(model.key)) { + keyString = model.key + } ob.addProperty("key", keyString) ob.addProperty("iv", iv) ob.addProperty("createdOn", Date().time) var success = false while (!success) { - val response: Response<*> = apiInterface.postDoc( - header, - "application/json", - Utilities.getUrl() + "/" + table, - ob - ).execute() - if (response.body() != null) { + val response: Response? = apiInterface?.postDoc(header, "application/json", Utilities.getUrl() + "/" + table, ob)?.execute() + if (response?.body() != null) { model.key = keyString model.iv = iv success = true @@ -158,21 +129,14 @@ class UploadToShelfService(context: Context) { } fun uploadHealth() { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync { realm: Realm -> - val myHealths: List = realm.where( - RealmMyHealthPojo::class.java - ).equalTo("isUpdated", true).notEqualTo("userId", "").findAll() + mRealm.executeTransactionAsync { realm: Realm -> + val myHealths: List = realm.where(RealmMyHealthPojo::class.java).equalTo("isUpdated", true).notEqualTo("userId", "").findAll() for (pojo in myHealths) { try { - val res = apiInterface.postDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/health", - serialize(pojo) - ).execute() - if (res.body() != null && res.body()!!.has("id")) { + val res = apiInterface?.postDoc(Utilities.header, "application/json", Utilities.getUrl() + "/health", serialize(pojo))?.execute() + if (res?.body() != null && res.body()?.has("id") == true) { pojo.set_rev(res.body()!!["rev"].asString) pojo.isUpdated = false } @@ -184,56 +148,37 @@ class UploadToShelfService(context: Context) { } private fun uploadToshelf(listener: SuccessListener) { - val apiInterface = client!!.create(ApiInterface::class.java) + val apiInterface = client?.create(ApiInterface::class.java) mRealm = dbService.realmInstance - mRealm!!.executeTransactionAsync( - { realm: Realm -> - val users = realm.where( - RealmUserModel::class.java - ).isNotEmpty("_id").findAll() - for (model in users) { - try { - if (model.id!!.startsWith("guest")) continue - val jsonDoc = apiInterface.getJsonObject( - Utilities.header, - Utilities.getUrl() + "/shelf/" + model._id - ).execute().body() - val `object` = getShelfData(realm, model.id, jsonDoc) - Utilities.log("JSON " + Gson().toJson(jsonDoc)) - val d = apiInterface.getJsonObject( - Utilities.header, - Utilities.getUrl() + "/shelf/" + model.id - ).execute().body() - `object`.addProperty("_rev", getString("_rev", d)) - apiInterface.putDoc( - Utilities.header, - "application/json", - Utilities.getUrl() + "/shelf/" + sharedPreferences.getString( - "userId", - "" - ), - `object` - ).execute().body() - } catch (e: Exception) { - e.printStackTrace() + mRealm.executeTransactionAsync({ realm: Realm -> + val users = realm.where(RealmUserModel::class.java).isNotEmpty("_id").findAll() + for (model in users) { + try { + if (model.id?.startsWith("guest") == true) { + continue } + val jsonDoc = apiInterface?.getJsonObject(Utilities.header, Utilities.getUrl() + "/shelf/" + model._id)?.execute()?.body() + val `object` = getShelfData(realm, model.id, jsonDoc) + Utilities.log("JSON " + Gson().toJson(jsonDoc)) + val d = apiInterface?.getJsonObject(Utilities.header, Utilities.getUrl() + "/shelf/" + model.id)?.execute()?.body() + `object`.addProperty("_rev", getString("_rev", d)) + apiInterface?.putDoc(Utilities.header, "application/json", Utilities.getUrl() + "/shelf/" + sharedPreferences.getString("userId", ""), `object`)?.execute()?.body() + } catch (e: Exception) { + e.printStackTrace() } - }, - { listener.onSuccess("Sync with server completed successfully") }) { err: Throwable? -> - listener.onSuccess( - "Unable to update documents." - ) + } }, + { listener.onSuccess("Sync with server completed successfully") }) { + listener.onSuccess("Unable to update documents.") } } private fun getShelfData(realm: Realm?, userId: String?, jsonDoc: JsonObject?): JsonObject { - val myLibs = getMyLibIds(realm!!, userId) + val myLibs = getMyLibIds(realm, userId) val myCourses = getMyCourseIds(realm, userId) val myMeetups = getMyMeetUpIds(realm, userId) - val removedResources = listOf(*removedIds(realm, "resources", userId!!)) + val removedResources = listOf(*removedIds(realm, "resources", userId)) val removedCourses = listOf(*removedIds(realm, "courses", userId)) - val mergedResourceIds = - mergeJsonArray(myLibs, getJsonArray("resourceIds", jsonDoc), removedResources) + val mergedResourceIds = mergeJsonArray(myLibs, getJsonArray("resourceIds", jsonDoc), removedResources) val mergedCoueseIds = mergeJsonArray(myCourses, getJsonArray("courseIds", jsonDoc), removedCourses) val `object` = JsonObject() `object`.addProperty("_id", sharedPreferences.getString("userId", "")) @@ -265,26 +210,26 @@ class UploadToShelfService(context: Context) { private set private fun changeUserSecurity(model: RealmUserModel, obj: JsonObject) { - val table = "userdb-" + Utilities.toHex(model.planetCode!!) + "-" + Utilities.toHex(model.name!!) + val table = "userdb-" + Utilities.toHex(model.planetCode) + "-" + Utilities.toHex(model.name) val header = "Basic " + Base64.encodeToString((obj["name"].asString + ":" + obj["password"].asString).toByteArray(), Base64.NO_WRAP) - val apiInterface = client!!.create(ApiInterface::class.java) - var response: Response + val apiInterface = client?.create(ApiInterface::class.java) + var response: Response? try { - response = apiInterface.getJsonObject(header, Utilities.getUrl() + "/" + table + "/_security").execute() - if (response.body() != null) { + response = apiInterface?.getJsonObject(header, Utilities.getUrl() + "/" + table + "/_security")?.execute() + if (response?.body() != null) { val jsonObject = response.body() - val members = jsonObject!!.getAsJsonObject("members") - val rolesArray: JsonArray = if (members.has("roles")) { + val members = jsonObject?.getAsJsonObject("members") + val rolesArray: JsonArray = if (members?.has("roles") == true) { members.getAsJsonArray("roles") } else { JsonArray() } rolesArray.add("health") - members.add("roles", rolesArray) - jsonObject.add("members", members) - response = apiInterface.putDoc(header, "application/json", Utilities.getUrl() + "/" + table + "/_security", jsonObject).execute() - if (response.body() != null) { - Utilities.log("Update security " + Gson().toJson(response.body())) + members?.add("roles", rolesArray) + jsonObject?.add("members", members) + response = apiInterface?.putDoc(header, "application/json", Utilities.getUrl() + "/" + table + "/_security", jsonObject)?.execute() + if (response?.body() != null) { + Utilities.log("Update security " + Gson().toJson(response?.body())) } } } catch (e: IOException) { diff --git a/app/src/main/java/org/ole/planet/myplanet/service/UserProfileDbHandler.kt b/app/src/main/java/org/ole/planet/myplanet/service/UserProfileDbHandler.kt index c06d73840c..e41ffb8bb4 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/UserProfileDbHandler.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/UserProfileDbHandler.kt @@ -32,7 +32,9 @@ class UserProfileDbHandler(context: Context) { .equalTo("id", settings.getString("userId", "")).findFirst() fun onLogin() { - if (!mRealm.isInTransaction) mRealm.beginTransaction() + if (!mRealm.isInTransaction) { + mRealm.beginTransaction() + } val offlineActivities = mRealm.copyToRealm(createUser()) offlineActivities.type = KEY_LOGIN offlineActivities._rev = null @@ -43,7 +45,9 @@ class UserProfileDbHandler(context: Context) { } fun onLogout() { - if (!mRealm.isInTransaction) mRealm.beginTransaction() + if (!mRealm.isInTransaction) { + mRealm.beginTransaction() + } val offlineActivities = getRecentLogin(mRealm) ?: return offlineActivities.logoutTime = Date().time mRealm.commitTransaction() @@ -71,9 +75,7 @@ class UserProfileDbHandler(context: Context) { get() = getOfflineVisits(userModel) fun getOfflineVisits(m: RealmUserModel?): Int { - val db_users = mRealm.where( - RealmOfflineActivity::class.java - ).equalTo("userName", m?.name).equalTo("type", KEY_LOGIN).findAll() + val db_users = mRealm.where(RealmOfflineActivity::class.java).equalTo("userName", m?.name).equalTo("type", KEY_LOGIN).findAll() return if (!db_users.isEmpty()) { db_users.size } else { diff --git a/app/src/main/java/org/ole/planet/myplanet/ui/dashboard/BaseDashboardFragment.kt b/app/src/main/java/org/ole/planet/myplanet/ui/dashboard/BaseDashboardFragment.kt index a155c97547..ff82e72575 100644 --- a/app/src/main/java/org/ole/planet/myplanet/ui/dashboard/BaseDashboardFragment.kt +++ b/app/src/main/java/org/ole/planet/myplanet/ui/dashboard/BaseDashboardFragment.kt @@ -379,7 +379,7 @@ open class BaseDashboardFragment : BaseDashboardFragmentPlugin(), NotificationCa Utilities.toast(activity, getString(R.string.myhealth_synced_successfully)) } - override fun onSyncFailed(msg: String) { + override fun onSyncFailed(msg: String?) { di?.dismiss() Utilities.toast(activity, getString(R.string.myhealth_synced_failed)) } diff --git a/app/src/main/java/org/ole/planet/myplanet/ui/library/AddResourceFragment.kt b/app/src/main/java/org/ole/planet/myplanet/ui/library/AddResourceFragment.kt index 2a0b2a1fe2..54e0f85ec2 100644 --- a/app/src/main/java/org/ole/planet/myplanet/ui/library/AddResourceFragment.kt +++ b/app/src/main/java/org/ole/planet/myplanet/ui/library/AddResourceFragment.kt @@ -131,14 +131,14 @@ class AddResourceFragment : BottomSheetDialogFragment() { floatingActionButton!!.setImageResource(R.drawable.ic_stop) } - override fun onRecordStopped(outputFile: String) { + override fun onRecordStopped(outputFile: String?) { tvTime!!.text = "" dialog.dismiss() audioStartIntent(outputFile) floatingActionButton!!.setImageResource(R.drawable.ic_mic) } - override fun onError(error: String) { + override fun onError(error: String?) { Utilities.toast(activity, error) } }) @@ -187,7 +187,7 @@ class AddResourceFragment : BottomSheetDialogFragment() { } } - private fun audioStartIntent(path: String) { + private fun audioStartIntent(path: String?) { if (!TextUtils.isEmpty(path)) { addResource(path) } else { @@ -206,7 +206,7 @@ class AddResourceFragment : BottomSheetDialogFragment() { return "" } - private fun addResource(path: String) { + private fun addResource(path: String?) { if (type == 0) { startActivity(Intent(activity, AddResourceActivity::class.java).putExtra("resource_local_url", path)) } else { diff --git a/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt b/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt index 21db89889c..c476b172f0 100644 --- a/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt +++ b/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt @@ -333,7 +333,7 @@ abstract class SyncActivity : ProcessUserDataActivity(), SyncListener, CheckVers progressDialog!!.show() } - override fun onSyncFailed(s: String) { + override fun onSyncFailed(s: String?) { if (::syncIconDrawable.isInitialized) { syncIconDrawable = syncIcon.drawable as AnimationDrawable syncIconDrawable.stop() @@ -532,7 +532,7 @@ abstract class SyncActivity : ProcessUserDataActivity(), SyncListener, CheckVers syncIconDrawable.selectDrawable(0) } - override fun onSyncFailed(msg: String) { + override fun onSyncFailed(msg: String?) { Utilities.toast(MainApplication.context, msg) progressDialog!!.dismiss() syncIconDrawable.stop() diff --git a/app/src/main/java/org/ole/planet/myplanet/ui/viewer/PDFReaderActivity.kt b/app/src/main/java/org/ole/planet/myplanet/ui/viewer/PDFReaderActivity.kt index 8c098165e6..aca79acde1 100644 --- a/app/src/main/java/org/ole/planet/myplanet/ui/viewer/PDFReaderActivity.kt +++ b/app/src/main/java/org/ole/planet/myplanet/ui/viewer/PDFReaderActivity.kt @@ -91,7 +91,7 @@ class PDFReaderActivity : AppCompatActivity(), OnPageChangeListener, OnLoadCompl activityPdfreaderBinding.fabRecord.setImageResource(R.drawable.ic_stop) } - override fun onRecordStopped(outputFile: String) { + override fun onRecordStopped(outputFile: String?) { Utilities.toast(this, getString(R.string.recording_stopped)) cancellAll(this) updateTranslation(outputFile) @@ -99,7 +99,7 @@ class PDFReaderActivity : AppCompatActivity(), OnPageChangeListener, OnLoadCompl activityPdfreaderBinding.fabRecord.setImageResource(R.drawable.ic_mic) } - private fun updateTranslation(outputFile: String) { + private fun updateTranslation(outputFile: String?) { if (this::library.isInitialized) { if (!mRealm.isInTransaction) mRealm.beginTransaction() library.translationAudioPath = outputFile @@ -115,7 +115,7 @@ class PDFReaderActivity : AppCompatActivity(), OnPageChangeListener, OnLoadCompl } } - override fun onError(error: String) { + override fun onError(error: String?) { cancellAll(this) Utilities.toast(this, error) activityPdfreaderBinding.fabRecord.setImageResource(R.drawable.ic_mic) diff --git a/app/src/main/java/org/ole/planet/myplanet/utilities/FileUtils.kt b/app/src/main/java/org/ole/planet/myplanet/utilities/FileUtils.kt index b1044a31e8..d45281bf18 100644 --- a/app/src/main/java/org/ole/planet/myplanet/utilities/FileUtils.kt +++ b/app/src/main/java/org/ole/planet/myplanet/utilities/FileUtils.kt @@ -118,9 +118,9 @@ object FileUtils { } @JvmStatic - fun installApk(activity: Context, file: String) { + fun installApk(activity: Context, file: String?) { try { - if (!file.endsWith("apk")) return + if (!file?.endsWith("apk")!!) return val toInstall = getSDPathFromUrl(file) toInstall.setReadable(true, false) val apkUri: Uri diff --git a/app/src/main/java/org/ole/planet/myplanet/utilities/Utilities.kt b/app/src/main/java/org/ole/planet/myplanet/utilities/Utilities.kt index a95e01044f..5b2be714d6 100644 --- a/app/src/main/java/org/ole/planet/myplanet/utilities/Utilities.kt +++ b/app/src/main/java/org/ole/planet/myplanet/utilities/Utilities.kt @@ -18,11 +18,9 @@ import org.ole.planet.myplanet.MainApplication.Companion.context import org.ole.planet.myplanet.R import org.ole.planet.myplanet.base.BaseRecyclerFragment.PREFS_NAME import org.ole.planet.myplanet.datamanager.MyDownloadService -import org.ole.planet.myplanet.model.RealmMyCourse import org.ole.planet.myplanet.model.RealmMyLibrary import java.lang.ref.WeakReference import java.math.BigInteger -import java.util.ArrayList object Utilities { private var contextRef: WeakReference? = null @@ -63,7 +61,7 @@ object Utilities { } @JvmStatic - fun toast(context: Context?, s: String) { + fun toast(context: Context?, s: String?) { context ?: return Toast.makeText(context, s, Toast.LENGTH_LONG).show() } @@ -189,7 +187,7 @@ object Utilities { return "$url/apkversion" } - fun getApkUpdateUrl(path: String): String { + fun getApkUpdateUrl(path: String?): String { val preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) var url = preferences.getString("couchdbURL", "") if (url != null) { @@ -200,8 +198,8 @@ object Utilities { return "$url$path" } - fun toHex(arg: String): String { - return String.format("%x", BigInteger(1, arg.toByteArray())) + fun toHex(arg: String?): String { + return String.format("%x", BigInteger(1, arg?.toByteArray())) } fun getMimeType(url: String?): String? {