Skip to content

Commit

Permalink
sync: more stability through safe call operators (fixes #3237) (#3238)
Browse files Browse the repository at this point in the history
Co-authored-by: dogi <[email protected]>
  • Loading branch information
Okuro3499 and dogi authored Mar 13, 2024
1 parent 8ac3682 commit 163f564
Show file tree
Hide file tree
Showing 20 changed files with 307 additions and 497 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -209,13 +210,15 @@ public List<RealmMyLibrary> filterLibraryByTag(String s, List<RealmTag> tags) {
}

public List<RealmMyCourse> filterCourseByTag(String s, List<RealmTag> tags) {
if (tags.size() == 0 && s.isEmpty()) {
if (tags.isEmpty() && s.isEmpty()) {
return applyCourseFilter((List<RealmMyCourse>) getList(RealmMyCourse.class));
}
List<RealmMyCourse> list = (List<RealmMyCourse>) 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<RealmMyCourse> list = (RealmResults<RealmMyCourse>) getData(s, RealmMyCourse.class);
if (isMyCourseLib) {
list = (RealmResults<RealmMyCourse>) RealmMyCourse.getMyCourseByUserId(model.id, list);
}
else list = (RealmResults<RealmMyCourse>) RealmMyCourse.getOurCourse(model.id, list);
if (tags.isEmpty()) return list;
RealmList<RealmMyCourse> courses = new RealmList<>();
for (RealmMyCourse course : list) {
checkAndAddToList(course, courses, tags);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ interface SyncListener {
@JvmSuppressWildcards
fun onSyncComplete()
@JvmSuppressWildcards
fun onSyncFailed(msg: String)
fun onSyncFailed(msg: String?)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -114,9 +115,9 @@ open class RealmMyCourse : RealmObject() {
}

@JvmStatic
fun getMyCourseByUserId(userId: String?, libs: List<RealmMyCourse>): List<RealmMyCourse> {
fun getMyCourseByUserId(userId: String?, libs: RealmResults<RealmMyCourse>?): List<RealmMyCourse> {
val libraries: MutableList<RealmMyCourse> = ArrayList()
for (item in libs) {
for (item in libs ?: emptyList()) {
if (item.userId!!.contains(userId)) {
libraries.add(item)
}
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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())
Expand Down Expand Up @@ -449,10 +449,10 @@ open class RealmMyLibrary : RealmObject() {
}

@JvmStatic
fun getMyLibIds(realm: Realm, userId: String?): JsonArray {
val myLibraries: List<RealmMyLibrary> = realm.where(RealmMyLibrary::class.java).contains("userId", userId).findAll()
fun getMyLibIds(realm: Realm?, userId: String?): JsonArray {
val myLibraries: RealmResults<RealmMyLibrary>? = 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,16 @@ open class RealmRemovedLog : RealmObject() {
}

@JvmStatic
fun removedIds(realm: Realm, type: String, userId: String): Array<String> {
val removedLibs = realm.where(RealmRemovedLog::class.java)
.equalTo("userId", userId)
.equalTo("type", type)
.findAll()
fun removedIds(realm: Realm?, type: String, userId: String?): Array<String> {
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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class AudioRecorderService {
audioRecordListener?.onRecordStarted()
} catch (e: Exception) {
myAudioRecorder = null
audioRecordListener?.onError(e.message!!)
audioRecordListener?.onError(e.message)
}
}
}
Expand Down Expand Up @@ -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?)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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>("download")
if (!download!!.failed && download.completeAll) {
installApk(context, download.fileUrl!!)
if (!download?.failed!! && download.completeAll) {
installApk(context, download.fileUrl)
}
}
}
Expand All @@ -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)
Expand All @@ -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)
}
}

Expand All @@ -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) {
Expand Down
24 changes: 12 additions & 12 deletions app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand All @@ -80,7 +80,7 @@ class SyncManager private constructor(private val context: Context) {
destroy()
}
}
td!!.start()
td?.start()
}

private fun startSync() {
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -144,20 +144,20 @@ 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<String?> = 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<String> = ArrayList()
for (i in 0 until rows.size()) {
val `object` = rows[i].asJsonObject
if (!TextUtils.isEmpty(getString("id", `object`))) keys.add(getString("key", `object`))
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<String?> = save(getJsonArray("rows", response.body()), mRealm)
newIds.addAll(ids)
}
Expand Down
Loading

0 comments on commit 163f564

Please sign in to comment.