Skip to content

Commit

Permalink
[] -- Refactor with Sonar, code as clean as possible (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zenin0 authored May 13, 2024
2 parents 520e973 + 583be2b commit 1610892
Show file tree
Hide file tree
Showing 33 changed files with 345 additions and 274 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import com.isanz.inmomarket.ui.home.HomeViewModel
import com.isanz.inmomarket.ui.profile.ProfileViewModel
import com.isanz.inmomarket.ui.search.SearchViewModel
import com.isanz.inmomarket.ui.settings.SettingsViewModel
import com.isanz.inmomarket.utils.Constants
import com.isanz.inmomarket.utils.entities.Message
import com.isanz.inmomarket.utils.entities.Property
import org.junit.Assert.*
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
import org.junit.runner.RunWith
import java.lang.reflect.Method
Expand Down Expand Up @@ -55,4 +54,4 @@ class InmomarketInstrumentedTest {
assertEquals("Hello", message.message )
assertEquals("123", message.senderId)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.isanz.inmomarket.InmoMarket
import com.isanz.inmomarket.R
import com.isanz.inmomarket.rv.propertyItem.PropertyItemViewModel
import com.isanz.inmomarket.utils.entities.Conversation
import com.isanz.inmomarket.utils.interfaces.OnItemClickListener
import kotlinx.coroutines.CoroutineScope
Expand Down Expand Up @@ -87,4 +86,4 @@ class ConversationListAdapter(private val listener: OnItemClickListener) :
private fun setImage(view: ImageView, uri: String) {
Glide.with(view.context).load(uri).circleCrop().into(view)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package com.isanz.inmomarket.rv.propertyItem

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.OneShotPreDrawListener
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
Expand All @@ -16,12 +22,6 @@ import com.isanz.inmomarket.R
import com.isanz.inmomarket.rv.extraItem.ExtraListAdapter
import com.isanz.inmomarket.utils.entities.Property
import com.isanz.inmomarket.utils.interfaces.OnItemClickListener
import androidx.recyclerview.widget.ItemTouchHelper
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat

class PropertyItemListAdapter(private val listener: OnItemClickListener) :
ListAdapter<Property, PropertyItemListAdapter.PropertyViewHolder>((PropertyItemDiffCallback())) {
Expand Down Expand Up @@ -56,14 +56,9 @@ class PropertyItemListAdapter(private val listener: OnItemClickListener) :
}

private fun setUpImage(holder: PropertyViewHolder, property: Property) {
holder.view.viewTreeObserver.addOnPreDrawListener(object :
ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
holder.view.viewTreeObserver.removeOnPreDrawListener(this)
loadImage(holder, property)
return true
}
})
OneShotPreDrawListener.add(holder.image) {
loadImage(holder, property)
}
}

private fun loadImage(holder: PropertyViewHolder, property: Property) {
Expand Down Expand Up @@ -147,4 +142,4 @@ class PropertyItemListAdapter(private val listener: OnItemClickListener) :
}


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class PropertyItemViewModel : ViewModel() {
fun getIfFavorite(property: Property, callback: (Boolean) -> Unit) {
val docRef = getDocumentReference(property)
docRef.get().addOnSuccessListener { document ->
val isFavorite = checkIfFavorite(document.get("favorites") as? List<*>)
val isFavorite = checkIfFavorite(document["favorites"] as? List<*>)
callback(isFavorite)
}
}
Expand All @@ -30,7 +30,7 @@ class PropertyItemViewModel : ViewModel() {
viewModelScope.launch {
val docRef = getDocumentReference(property)
docRef.get().addOnSuccessListener { document ->
val favorites = document.get("favorites") as? List<*>
val favorites = document["favorites"] as? List<*>
if (checkIfFavorite(favorites)) {
removeFavorite(docRef, updateFavoriteIcon)
} else {
Expand Down Expand Up @@ -59,4 +59,4 @@ class PropertyItemViewModel : ViewModel() {
fun deleteProperty(property: Property) {
getDocumentReference(property).delete()
}
}
}
32 changes: 19 additions & 13 deletions app/src/main/java/com/isanz/inmomarket/ui/add/AddFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
Expand All @@ -23,7 +24,7 @@ import com.isanz.inmomarket.rv.imageItem.ImageListAdapter
import com.isanz.inmomarket.utils.Constants
import java.util.UUID

@Suppress("DEPRECATION")

class AddFragment : Fragment() {


Expand All @@ -38,13 +39,17 @@ class AddFragment : Fragment() {
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
mBinding = FragmentAddBinding.inflate(inflater, container, false)
setUp()
return mBinding.root
}

private fun setUp() {
db = InmoMarket.getDb()
setupImageListAdapter()
initializePlaces()
setupAddressClickListener()
setUpButtons()
setUpDrawables()
return mBinding.root
}

private fun setupImageListAdapter() {
Expand All @@ -68,7 +73,7 @@ class AddFragment : Fragment() {
val fields = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS)
val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields)
.build(requireContext())
startActivityForResult(intent, Constants.REQUEST_CODE_AUTOCOMPLETE)
placeAutocompleteLauncher.launch(intent)
}

private fun setUpDrawables() {
Expand Down Expand Up @@ -202,21 +207,22 @@ class AddFragment : Fragment() {
type = "image/*"
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
}
startActivityForResult(intent, Constants.REQUEST_CODE_PICK_IMAGES)
imagePickerResultLauncher.launch(intent)
}

private val imagePickerResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
handleImagePickResult(result.data)
}
}

@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == Constants.REQUEST_CODE_PICK_IMAGES && resultCode == Activity.RESULT_OK) {
handleImagePickResult(data)
} else if (requestCode == Constants.REQUEST_CODE_AUTOCOMPLETE && resultCode == Activity.RESULT_OK) {
handlePlaceAutocompleteResult(data!!)
private val placeAutocompleteLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
handlePlaceAutocompleteResult(result.data!!)
}
}


private fun handleImagePickResult(data: Intent?) {
val imageUris = extractImageUrisFromIntent(data)
val adapter = (mBinding.rvImages.adapter as? ImageListAdapter)
Expand Down Expand Up @@ -246,4 +252,4 @@ class AddFragment : Fragment() {
val place = Autocomplete.getPlaceFromIntent(data)
mBinding.tieAddress.setText(place.address)
}
}
}
13 changes: 5 additions & 8 deletions app/src/main/java/com/isanz/inmomarket/ui/chat/ChatFragment.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package com.isanz.inmomarket.ui.chat

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
Expand Down Expand Up @@ -34,7 +32,7 @@ class ChatFragment : Fragment() {
recipientId = InmoMarket.getAuth().currentUser?.uid!!
}

@RequiresApi(Build.VERSION_CODES.O)

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
Expand All @@ -43,7 +41,7 @@ class ChatFragment : Fragment() {
return mBinding.root
}

@RequiresApi(Build.VERSION_CODES.O)

private fun setUpView() {
setUpOtherUser()
setUpButtons()
Expand Down Expand Up @@ -81,7 +79,7 @@ class ChatFragment : Fragment() {
Glide.with(this).load(imageUri).circleCrop().into(mBinding.ivProfileChat)
}

@RequiresApi(Build.VERSION_CODES.O)

private fun setUpButtons() {
mBinding.fabSendMessage.setOnClickListener {
lifecycleScope.launch {
Expand All @@ -93,8 +91,7 @@ class ChatFragment : Fragment() {
}
}

@RequiresApi(Build.VERSION_CODES.O)
private suspend fun sendMessage() {
private fun sendMessage() {
val text = mBinding.tieMessage.text.toString()
chatViewModel.sendMessage(text, idChat, recipientId)
mBinding.tieMessage.text?.clear()
Expand All @@ -103,4 +100,4 @@ class ChatFragment : Fragment() {
private fun navigateBack() {
this.findNavController().popBackStack()
}
}
}
47 changes: 26 additions & 21 deletions app/src/main/java/com/isanz/inmomarket/ui/chat/ChatViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package com.isanz.inmomarket.ui.chat

import android.content.ContentValues.TAG
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
Expand All @@ -17,47 +16,53 @@ import com.google.firebase.ktx.Firebase
import com.isanz.inmomarket.utils.entities.Conversation
import com.isanz.inmomarket.utils.entities.Message
import com.isanz.inmomarket.utils.entities.User
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class ChatViewModel : ViewModel() {
class ChatViewModel(private val dispatcher: CoroutineDispatcher = Dispatchers.IO) : ViewModel() {

private val database: FirebaseDatabase = Firebase.database
private val _messageList = MutableLiveData<List<Message>>()
val messageList: LiveData<List<Message>> get() = _messageList

@RequiresApi(Build.VERSION_CODES.O)
suspend fun sendMessage(text: String, chatId: String, senderId: String) {
val message = createMessage(text, senderId)
try {
withContext(Dispatchers.IO) {
private val _messageSentStatus = MutableLiveData<Boolean>()

fun sendMessage(text: String, chatId: String, senderId: String) {
viewModelScope.launch(dispatcher) {
val message = createMessage(text, senderId)
try {
database.getReference("chatMessages").child(chatId).push().setValue(message).await()
database.getReference("chats").child(chatId).child("lastMessage").setValue(message).await()
database.getReference("chats").child(chatId).child("lastMessage").setValue(message)
.await()
_messageSentStatus.postValue(true)
} catch (e: Exception) {
Log.e(TAG, "sendMessage:failure", e)
_messageSentStatus.postValue(false)
}
} catch (e: Exception) {
Log.e(TAG, "sendMessage:failure", e)
}
}

@RequiresApi(Build.VERSION_CODES.O)

private fun createMessage(text: String, senderId: String): Message {
val current = LocalDateTime.now()
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
val current = Calendar.getInstance().time
val dateFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val timeFormatter = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
return Message(
message = text,
senderId = senderId,
messageDate = current.format(dateFormatter),
messageTime = current.format(timeFormatter)
messageDate = dateFormatter.format(current),
messageTime = timeFormatter.format(current)
)
}

Expand Down Expand Up @@ -129,4 +134,4 @@ class ChatViewModel : ViewModel() {
}
_messageList.value = tempList
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
Expand Down Expand Up @@ -78,4 +77,4 @@ class ConversationsFragment : Fragment(), OnItemClickListener {
}
findNavController().navigate(R.id.action_navigation_messages_to_navigation_chat, bundle)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class ConversationsViewModel : ViewModel() {
private val userId = InmoMarket.getAuth().currentUser!!.uid

@RequiresApi(Build.VERSION_CODES.O)
fun sortConversations(conversations: MutableList<Conversation>): List<Conversation> {
fun sortConversations(conversations: List<Conversation>): List<Conversation> {
return conversations.sortedByDescending {
if (it.lastMessage.messageDate.isNotBlank() && it.lastMessage.messageTime.isNotBlank()) {
val dateTimeStr = "${it.lastMessage.messageDate} ${it.lastMessage.messageTime}"
Expand Down Expand Up @@ -62,12 +62,12 @@ class ConversationsViewModel : ViewModel() {
}

override fun onCancelled(error: com.google.firebase.database.DatabaseError) {

Log.w(Constants.TAG, "retrieveConversations:onCancelled", error.toException())
}
}
chatsRef.addValueEventListener(messageListener)
} catch (e: Exception) {
Log.e(Constants.TAG, "retrieveConversations:failure", e)
}
}
}
}
Loading

0 comments on commit 1610892

Please sign in to comment.