Skip to content

Commit

Permalink
news: smoother sync (fixes open-learning-exchange#3180) (open-learnin…
Browse files Browse the repository at this point in the history
…g-exchange#3181)

Co-authored-by: dogi <[email protected]>
  • Loading branch information
Okuro3499 and dogi authored Mar 1, 2024
1 parent e27a633 commit e171c1e
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 80 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 1383
versionName "0.13.83"
versionCode 1384
versionName "0.13.84"
ndkVersion '21.3.6528147'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
Expand Down
70 changes: 37 additions & 33 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmNews.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,23 +62,23 @@ open class RealmNews : RealmObject() {
val labelsArray: JsonArray
get() {
val array = JsonArray()
for (s in labels!!) {
labels?.forEach{ s ->
array.add(s)
}
return array
}

fun addLabel(label: String?) {
if (!labels!!.contains(label)) {
if (label != null && !labels?.contains(label)!!) {
Utilities.log("Added")
labels!!.add(label)
labels?.add(label)
}
}

fun setLabels(images: JsonArray) {
labels = RealmList()
for (ob in images) {
labels!!.add(ob.asString)
labels?.add(ob.asString)
}
}

Expand All @@ -105,7 +105,7 @@ open class RealmNews : RealmObject() {
Utilities.log(ms)
}
for (ob in imagesArray) {
ms = ms!!.replace(JsonUtils.getString("markdown", ob.asJsonObject), "")
ms = ms?.replace(JsonUtils.getString("markdown", ob.asJsonObject), "")
}
return ms
}
Expand All @@ -130,35 +130,39 @@ open class RealmNews : RealmObject() {
companion object {
@JvmStatic
fun insert(mRealm: Realm, doc: JsonObject?) {
Utilities.log("sync nnews " + Gson().toJson(doc))
var news = mRealm.where(RealmNews::class.java).equalTo("_id", JsonUtils.getString("_id", doc)).findFirst()
if (news == null) {
news = mRealm.createObject(RealmNews::class.java, JsonUtils.getString("_id", doc))
mRealm.executeTransactionAsync { realm ->
Utilities.log("sync nnews " + Gson().toJson(doc))
var news = realm.where(RealmNews::class.java)
.equalTo("_id", JsonUtils.getString("_id", doc))
.findFirst()
if (news == null) {
news = realm.createObject(RealmNews::class.java, JsonUtils.getString("_id", doc))
}
news?.set_rev(JsonUtils.getString("_rev", doc))
news?.set_id(JsonUtils.getString("_id", doc))
news?.viewableBy = JsonUtils.getString("viewableBy", doc)
news?.docType = JsonUtils.getString("docType", doc)
news?.avatar = JsonUtils.getString("avatar", doc)
news?.updatedDate = JsonUtils.getLong("updatedDate", doc)
news?.viewableId = JsonUtils.getString("viewableId", doc)
news?.createdOn = JsonUtils.getString("createdOn", doc)
news?.messageType = JsonUtils.getString("messageType", doc)
news?.messagePlanetCode = JsonUtils.getString("messagePlanetCode", doc)
news?.replyTo = JsonUtils.getString("replyTo", doc)
news?.parentCode = JsonUtils.getString("parentCode", doc)
val user = JsonUtils.getJsonObject("user", doc)
news?.user = Gson().toJson(JsonUtils.getJsonObject("user", doc))
news?.userId = JsonUtils.getString("_id", user)
news?.userName = JsonUtils.getString("name", user)
news?.time = JsonUtils.getLong("time", doc)
val images = JsonUtils.getJsonArray("images", doc)
val message = JsonUtils.getString("message", doc)
news?.message = message
news?.images = Gson().toJson(images)
val labels = JsonUtils.getJsonArray("labels", doc)
news?.viewIn = Gson().toJson(JsonUtils.getJsonArray("viewIn", doc))
news?.setLabels(labels)
}
news!!.set_rev(JsonUtils.getString("_rev", doc))
news.set_id(JsonUtils.getString("_id", doc))
news.viewableBy = JsonUtils.getString("viewableBy", doc)
news.docType = JsonUtils.getString("docType", doc)
news.avatar = JsonUtils.getString("avatar", doc)
news.updatedDate = JsonUtils.getLong("updatedDate", doc)
news.viewableId = JsonUtils.getString("viewableId", doc)
news.createdOn = JsonUtils.getString("createdOn", doc)
news.messageType = JsonUtils.getString("messageType", doc)
news.messagePlanetCode = JsonUtils.getString("messagePlanetCode", doc)
news.replyTo = JsonUtils.getString("replyTo", doc)
news.parentCode = JsonUtils.getString("parentCode", doc)
val user = JsonUtils.getJsonObject("user", doc)
news.user = Gson().toJson(JsonUtils.getJsonObject("user", doc))
news.userId = JsonUtils.getString("_id", user)
news.userName = JsonUtils.getString("name", user)
news.time = JsonUtils.getLong("time", doc)
val images = JsonUtils.getJsonArray("images", doc)
val message = JsonUtils.getString("message", doc)
news.message = message
news.images = Gson().toJson(images)
val labels = JsonUtils.getJsonArray("labels", doc)
news.viewIn = Gson().toJson(JsonUtils.getJsonArray("viewIn", doc))
news.setLabels(labels)
}

@JvmStatic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import android.widget.LinearLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import io.realm.Case
import io.realm.RealmResults
import io.realm.Sort
import org.ole.planet.myplanet.base.BaseContainerFragment
import org.ole.planet.myplanet.databinding.FragmentCommunityBinding
Expand All @@ -24,8 +25,8 @@ import org.ole.planet.myplanet.utilities.Utilities

class CommunityFragment : BaseContainerFragment(), AdapterNews.OnNewsItemClickListener {
private lateinit var fragmentCommunityBinding: FragmentCommunityBinding
override fun addImage(llImage: LinearLayout?) {
}
private var newList: RealmResults<RealmNews>? = null
override fun addImage(llImage: LinearLayout?) {}

override fun showReply(news: RealmNews?, fromLogin: Boolean) {
if (news != null) {
Expand All @@ -41,6 +42,14 @@ class CommunityFragment : BaseContainerFragment(), AdapterNews.OnNewsItemClickLi
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
fragmentCommunityBinding = FragmentCommunityBinding.inflate(inflater, container, false)
newList = mRealm.where(RealmNews::class.java).equalTo("docType", "message", Case.INSENSITIVE)
.equalTo("viewableBy", "community", Case.INSENSITIVE)
.equalTo("createdOn", user?.planetCode, Case.INSENSITIVE).isEmpty("replyTo")
.sort("time", Sort.DESCENDING).findAll()

newList?.addChangeListener { results ->
updatedNewsList(results)
}
return fragmentCommunityBinding.root
}

Expand All @@ -51,22 +60,13 @@ class CommunityFragment : BaseContainerFragment(), AdapterNews.OnNewsItemClickLi
fragmentCommunityBinding.btnLibrary.setOnClickListener {
homeItemClickListener?.openCallFragment(LibraryFragment())
}
val list =
mRealm.where(RealmNews::class.java).equalTo("docType", "message", Case.INSENSITIVE)
newList = mRealm.where(RealmNews::class.java).equalTo("docType", "message", Case.INSENSITIVE)
.equalTo("viewableBy", "community", Case.INSENSITIVE)
.equalTo("createdOn", user?.planetCode, Case.INSENSITIVE).isEmpty("replyTo")
.sort("time", Sort.DESCENDING).findAll()
val orientation = resources.configuration.orientation
changeLayoutManager(orientation)

Utilities.log("list size " + list.size)
val adapter = activity?.let { AdapterNews(it, list, user, null) }
adapter?.setListener(this)
adapter?.setFromLogin(requireArguments().getBoolean("fromLogin", false))
adapter?.setmRealm(mRealm)
fragmentCommunityBinding.rvCommunity.adapter = adapter
fragmentCommunityBinding.llEditDelete.visibility = if (user!!.isManager()) View.VISIBLE else View.GONE

updatedNewsList(newList)
}

override fun onConfigurationChanged(newConfig: Configuration) {
Expand All @@ -82,4 +82,17 @@ class CommunityFragment : BaseContainerFragment(), AdapterNews.OnNewsItemClickLi
fragmentCommunityBinding.rvCommunity.layoutManager = LinearLayoutManager(activity)
}
}

private fun updatedNewsList(updatedList: RealmResults<RealmNews>?) {
activity?.runOnUiThread {
val updatedListAsMutable: MutableList<RealmNews?> = updatedList?.toMutableList() ?: mutableListOf()
val adapter = activity?.let { AdapterNews(it, updatedListAsMutable, user, null) }
adapter?.setListener(this)
adapter?.setFromLogin(requireArguments().getBoolean("fromLogin", false))
adapter?.setmRealm(mRealm)
fragmentCommunityBinding.rvCommunity.adapter = adapter
fragmentCommunityBinding.llEditDelete.visibility = if (user?.isManager() == true) View.VISIBLE else View.GONE
adapter?.notifyDataSetChanged()
}
}
}
90 changes: 65 additions & 25 deletions app/src/main/java/org/ole/planet/myplanet/ui/news/NewsFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver
import com.google.gson.Gson
import com.google.gson.JsonArray
import io.realm.Case
import io.realm.RealmResults
import io.realm.Sort
import org.ole.planet.myplanet.R
import org.ole.planet.myplanet.base.BaseNewsFragment
Expand All @@ -29,30 +30,70 @@ import org.ole.planet.myplanet.utilities.Constants.showBetaFeature
import org.ole.planet.myplanet.utilities.FileUtils.openOleFolder
import org.ole.planet.myplanet.utilities.JsonUtils.getString
import org.ole.planet.myplanet.utilities.KeyboardUtils.setupUI
import org.ole.planet.myplanet.utilities.Utilities

@RequiresApi(api = Build.VERSION_CODES.O)
class NewsFragment : BaseNewsFragment() {
private lateinit var fragmentNewsBinding: FragmentNewsBinding
var user: RealmUserModel? = null
private var updatedNewsList: RealmResults<RealmNews>? = null
private var filteredNewsList: List<RealmNews?> = listOf()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
fragmentNewsBinding = FragmentNewsBinding.inflate(inflater, container, false)
llImage = fragmentNewsBinding.llImages
mRealm = DatabaseService(requireActivity()).realmInstance
user = UserProfileDbHandler(requireContext()).userModel
setupUI(fragmentNewsBinding.newsFragmentParentLayout, requireActivity())
fragmentNewsBinding.btnAddStory.setOnClickListener {
fragmentNewsBinding.llAddNews.visibility = if (fragmentNewsBinding.llAddNews.visibility == View.VISIBLE) View.GONE else View.VISIBLE
fragmentNewsBinding.btnAddStory.text = if (fragmentNewsBinding.llAddNews.visibility == View.VISIBLE) getString(R.string.hide_add_story) else getString(
R.string.add_story
)
fragmentNewsBinding.llAddNews.visibility = if (fragmentNewsBinding.llAddNews.visibility == View.VISIBLE) {
View.GONE
} else {
View.VISIBLE
}
fragmentNewsBinding.btnAddStory.text = if (fragmentNewsBinding.llAddNews.visibility == View.VISIBLE) {
getString(R.string.hide_add_story)
} else {
getString(R.string.add_story)
}
}
if (requireArguments().getBoolean("fromLogin")) {
fragmentNewsBinding.btnAddStory.visibility = View.GONE
fragmentNewsBinding.llAddNews.visibility = View.GONE
}

updatedNewsList = mRealm.where(RealmNews::class.java).sort("time", Sort.DESCENDING)
.isEmpty("replyTo").equalTo("docType", "message", Case.INSENSITIVE)
.findAllAsync()

updatedNewsList?.addChangeListener { results ->
filteredNewsList = filterNewsList(results)
setData(filteredNewsList)
}
return fragmentNewsBinding.root
}

private fun filterNewsList(results: RealmResults<RealmNews>): List<RealmNews?> {
val filteredList: MutableList<RealmNews?> = ArrayList()
for (news in results) {
if (news.viewableBy.equals("community", ignoreCase = true)) {
filteredList.add(news)
continue
}

if (!news.viewIn.isNullOrEmpty()) {
val ar = Gson().fromJson(news.viewIn, JsonArray::class.java)
for (e in ar) {
val ob = e.asJsonObject
if (ob != null && ob.has("_id") && ob["_id"].asString.equals("${user?.planetCode}@${user?.parentCode}", ignoreCase = true)) {
filteredList.add(news)
break
}
}
}
}
return filteredList
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setData(newsList)
Expand All @@ -72,8 +113,8 @@ class NewsFragment : BaseNewsFragment() {

val n = user?.let { it1 -> createNews(map, mRealm, it1, imageList) }
imageList.clear()
llImage!!.removeAllViews()
adapterNews!!.addItem(n)
llImage?.removeAllViews()
adapterNews?.addItem(n)
setData(newsList)
}

Expand All @@ -99,11 +140,7 @@ class NewsFragment : BaseNewsFragment() {
val ar = Gson().fromJson(news.viewIn, JsonArray::class.java)
for (e in ar) {
val ob = e.asJsonObject
if (ob != null && ob.has("_id") && ob["_id"].asString.equals(
if (user != null) user!!.planetCode + "@" + user!!.parentCode else "",
ignoreCase = true
)
) {
if (ob != null && ob.has("_id") && ob["_id"].asString.equals(if (user != null) user?.planetCode + "@" + user?.parentCode else "", ignoreCase = true)) {
list.add(news)
}
}
Expand All @@ -115,11 +152,13 @@ class NewsFragment : BaseNewsFragment() {
override fun setData(list: List<RealmNews?>?) {
changeLayoutManager(resources.configuration.orientation, fragmentNewsBinding.rvNews)
val resourceIds: MutableList<String> = ArrayList()
for (news in list!!) {
if (news!!.imagesArray.size() > 0) {
val ob = news.imagesArray[0].asJsonObject
val resourceId = getString("resourceId", ob.asJsonObject)
resourceIds.add(resourceId)
list?.forEach { news ->
if ((news?.imagesArray?.size() ?: 0) > 0) {
val ob = news?.imagesArray?.get(0)?.asJsonObject
val resourceId = getString("resourceId", ob?.asJsonObject)
resourceId.let {
resourceIds.add(it)
}
}
}
val urls = ArrayList<String>()
Expand All @@ -129,15 +168,16 @@ class NewsFragment : BaseNewsFragment() {
.`in`("_id", stringArray)
.findAll()
getUrlsAndStartDownload(lib, settings, urls)
adapterNews = activity?.let { AdapterNews(it, list.toMutableList(), user, null) }
adapterNews!!.setmRealm(mRealm)
adapterNews!!.setFromLogin(requireArguments().getBoolean("fromLogin"))
adapterNews!!.setListener(this)
adapterNews!!.registerAdapterDataObserver(observer)
adapterNews = activity?.let { AdapterNews(it, list?.toMutableList() ?: mutableListOf(), user, null) }
adapterNews?.setmRealm(mRealm)
adapterNews?.setFromLogin(requireArguments().getBoolean("fromLogin"))
adapterNews?.setListener(this)
adapterNews?.registerAdapterDataObserver(observer)
fragmentNewsBinding.rvNews.adapter = adapterNews
showNoData(fragmentNewsBinding.tvMessage, adapterNews!!.itemCount)
adapterNews?.let { showNoData(fragmentNewsBinding.tvMessage, it.itemCount) }
fragmentNewsBinding.llAddNews.visibility = View.GONE
fragmentNewsBinding.btnAddStory.text = getString(R.string.add_story)
adapterNews?.notifyDataSetChanged()
}

override fun onConfigurationChanged(newConfig: Configuration) {
Expand All @@ -148,15 +188,15 @@ class NewsFragment : BaseNewsFragment() {

private val observer: AdapterDataObserver = object : AdapterDataObserver() {
override fun onChanged() {
showNoData(fragmentNewsBinding.tvMessage, adapterNews!!.itemCount)
adapterNews?.let { showNoData(fragmentNewsBinding.tvMessage, it.itemCount) }
}

override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
showNoData(fragmentNewsBinding.tvMessage, adapterNews!!.itemCount)
adapterNews?.let { showNoData(fragmentNewsBinding.tvMessage, it.itemCount) }
}

override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
showNoData(fragmentNewsBinding.tvMessage, adapterNews!!.itemCount)
adapterNews?.let { showNoData(fragmentNewsBinding.tvMessage, it.itemCount) }
}
}
}
Loading

0 comments on commit e171c1e

Please sign in to comment.