Open Odomhae opened 3 years ago
package kr.co.openit.openrider.service.main.fragment
import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.LinearLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.realm.Realm import io.realm.RealmList import io.realm.Sort import io.realm.kotlin.createObject import io.realm.kotlin.where import kotlinx.android.synthetic.main.fragment_main_chat. import kotlinx.android.synthetic.main.list_item_main_chat.view. import kotlinx.coroutines. import kr.co.openit.openrider.R import kr.co.openit.openrider.common.constants.OpenriderConstants import kr.co.openit.openrider.common.constants.OpenriderConstants.RequestParamName import kr.co.openit.openrider.common.constants.OpenriderConstants.ResponseParamName import kr.co.openit.openrider.common.fragments.BaseFragment import kr.co.openit.openrider.common.preference.PreferenceUtilProfile import kr.co.openit.openrider.common.realm.ChatMember import kr.co.openit.openrider.common.realm.ChatRoom import kr.co.openit.openrider.common.utils.AesssUtil import kr.co.openit.openrider.common.utils.GlideUtil import kr.co.openit.openrider.common.utils.OpenriderUtil import kr.co.openit.openrider.service.chat.activity.ChatRoomCreateActivity import kr.co.openit.openrider.service.chat.activity.ChatRoomMessageActivity import kr.co.openit.openrider.service.chat.service.ChatService import org.json.JSONObject import java.text.SimpleDateFormat import java.util. import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.resume
class MainChatFragment : BaseFragment() {
val realm = Realm.getDefaultInstance() var realmListChatRooms: RealmList<ChatRoom> = RealmList() var preferenceUtilProfile: PreferenceUtilProfile? = null val nCurrentPage = 0 lateinit var lLayoutNodata: LinearLayout lateinit var recyclerView: RecyclerView companion object { fun newInstance() = MainChatFragment().apply { arguments = Bundle().apply { } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_main_chat, container, false) preferenceUtilProfile = PreferenceUtilProfile(requireContext()) recyclerView = view.findViewById(R.id.community_chat_room_rv_chat_room) recyclerView.setHasFixedSize(true) recyclerView.overScrollMode = View.OVER_SCROLL_NEVER val ibCreate = view.findViewById<ImageButton>(R.id.community_chat_room_ib_create_room) ibCreate.setOnClickListener { //채팅방 생성 val intent = Intent(requireContext(), ChatRoomCreateActivity::class.java) startActivity(intent) } //JobSelectListChatRoom.start() startCoroutine() return view } override fun onDestroy() { super.onDestroy() // cancel() // TODO: 3/30/21 // realm.close() } override fun title(): String { return "ChatRoomList" } override fun loadDataFragment() { } override fun sendDataFromActivity(strKey: String?, objData: Any?) { //nothing } fun startCoroutine() = runBlocking<Unit> { val one = async(start = CoroutineStart.LAZY) { JobSelectListChatRoom() } one.start() // async(start = CoroutineStart.LAZY) { JobSelectListChatRoom() }.start() Log.d("======yesss", "sth") } override fun onResume() { super.onResume() // 다시 로딩 startCoroutine() } private fun insertChatRoomListData(resultJSON: JSONObject) { try { //채팅방 목록 if (OpenriderUtil.isHasJSONData(resultJSON, ResponseParamName.LIST)) { val resultChatRoomListJSONArray = resultJSON.getJSONArray(ResponseParamName.LIST) if (resultChatRoomListJSONArray.length() > 0) { realm.beginTransaction() for (i in 0 until resultChatRoomListJSONArray.length()) { val chatRoomJSON = resultChatRoomListJSONArray.getJSONObject(i) if (OpenriderUtil.isHasJSONData(chatRoomJSON, "ROOM_SEQ")) { val roomSeq = chatRoomJSON.getLong("ROOM_SEQ") val chatMembers: RealmList<ChatMember> = RealmList() if (OpenriderUtil.isHasJSONData(chatRoomJSON, "PARTICIPANT")) { //채팅 멤버 처리 val participantJSONArray = chatRoomJSON.getJSONArray("PARTICIPANT") for (j in 0 until participantJSONArray.length()) { //채팅멤버 DB 추가 및 업데이트 val participantJSON = participantJSONArray.getJSONObject(j) if (OpenriderUtil.isHasJSONData(participantJSON, "MEMBER_SEQ")) { val memberSeq = participantJSON.getLong("MEMBER_SEQ") val realmQueryChatMember = realm.where<ChatMember>().equalTo("idMember", memberSeq).findFirst() if (realmQueryChatMember != null) { //채팅 멤버 업데이트 if (OpenriderUtil.isHasJSONData(participantJSON, "NICK_NAME")) { realmQueryChatMember.nickName = participantJSON.getString("NICK_NAME") } if (OpenriderUtil.isHasJSONData(participantJSON, "PROFILE_URL")) { realmQueryChatMember.profileUrl = participantJSON.getString("PROFILE_URL") } if (OpenriderUtil.isHasJSONData(participantJSON, "LEVEL")) { realmQueryChatMember.level = participantJSON.getLong("LEVEL") } if (OpenriderUtil.isHasJSONData(participantJSON, "EMAIL")) { realmQueryChatMember.email = participantJSON.getString("EMAIL") } if (OpenriderUtil.isHasJSONData(participantJSON, "SPONSOR")) { realmQueryChatMember.sponsor = participantJSON.getString("SPONSOR") } if (OpenriderUtil.isHasJSONData(participantJSON, "MANIA")) { realmQueryChatMember.sponsor = participantJSON.getString("MANIA") } chatMembers.add(realm.copyToRealm(realmQueryChatMember)) } else { //채팅 멤버 생성 val idMax = realm.where<ChatMember>().max("id") val id = idMax?.toLong()?.plus(1L) ?: 0L val chatMember = realm.createObject<ChatMember>(id) chatMember.idMember = memberSeq if (OpenriderUtil.isHasJSONData(participantJSON, "NICK_NAME")) { chatMember.nickName = participantJSON.getString("NICK_NAME") } if (OpenriderUtil.isHasJSONData(participantJSON, "PROFILE_URL")) { chatMember.profileUrl = participantJSON.getString("PROFILE_URL") } if (OpenriderUtil.isHasJSONData(participantJSON, "LEVEL")) { chatMember.level = participantJSON.getLong("LEVEL") } if (OpenriderUtil.isHasJSONData(participantJSON, "EMAIL")) { chatMember.email = participantJSON.getString("EMAIL") } if (OpenriderUtil.isHasJSONData(participantJSON, "SPONSOR")) { chatMember.sponsor = participantJSON.getString("SPONSOR") } if (OpenriderUtil.isHasJSONData(participantJSON, "MANIA")) { chatMember.sponsor = participantJSON.getString("MANIA") } chatMembers.add(realm.copyToRealm(chatMember)) } } } } //채팅방 처리 val realmQueryChatRoom = realm.where<ChatRoom>().equalTo("idRoom", roomSeq).findFirst() if (realmQueryChatRoom != null) { //채팅방 업데이트 if (OpenriderUtil.isHasJSONData(chatRoomJSON, "MESSAGE_SEQ")) { realmQueryChatRoom.idServerLastMessage = chatRoomJSON.getLong("MESSAGE_SEQ") }
// if (OpenriderUtil.isHasJSONData(chatRoomJSON, "TITLE")) { // realmQueryChatRoom.name = chatRoomJSON.getString("TITLE") // }
if (OpenriderUtil.isHasJSONData(chatRoomJSON, "INS_DT")) { realmQueryChatRoom.lastMessageDateInsert = chatRoomJSON.getString("INS_DT") } if (OpenriderUtil.isHasJSONData(chatRoomJSON, "CONTENT")) { realmQueryChatRoom.lastMessageContent = chatRoomJSON.getString("CONTENT") } realmQueryChatRoom.chatMembers = chatMembers } else { //채팅방 생성 val idMax = realm.where<ChatRoom>().max("id") val id = idMax?.toLong()?.plus(1L) ?: 0L val chatRoom = realm.createObject<ChatRoom>(id) chatRoom.idRoom = roomSeq if (OpenriderUtil.isHasJSONData(chatRoomJSON, "MEMBER_SEQ")) { chatRoom.idMember = chatRoomJSON.getLong("MEMBER_SEQ") } if (OpenriderUtil.isHasJSONData(chatRoomJSON, "MESSAGE_SEQ")) { chatRoom.idServerLastMessage = chatRoomJSON.getLong("MESSAGE_SEQ") }
// if (OpenriderUtil.isHasJSONData(chatRoomJSON, "TITLE")) { // chatRoom.name = chatRoomJSON.getString("TITLE") // }
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") simpleDateFormat.timeZone = TimeZone.getTimeZone("GMT") chatRoom.dateInsert = simpleDateFormat.format(Date()) if (OpenriderUtil.isHasJSONData(chatRoomJSON, "INS_DT")) { chatRoom.lastMessageDateInsert = chatRoomJSON.getString("INS_DT") } if (OpenriderUtil.isHasJSONData(chatRoomJSON, "CONTENT")) { chatRoom.lastMessageContent = chatRoomJSON.getString("CONTENT") } chatRoom.chatMembers = chatMembers } } } realm.commitTransaction() } } } catch (e: Exception) { e.printStackTrace() } getChatRoomListData() } fun getChatRoomListData() { try { val realmResults = realm.where<ChatRoom>().findAll() .sort("dateInsert", Sort.DESCENDING) .sort("lastMessageDateInsert", Sort.DESCENDING) if (realmResults.size > 0) { realmListChatRooms.clear() realmListChatRooms.addAll(realmResults.subList(0, realmResults.size)) }else{ community_chat_room_llayout_nodata.visibility = View.VISIBLE } setChatRoomList() } catch (e: Exception) { e.printStackTrace() } } fun setChatRoomList() { recyclerView.adapter = CommunityChatRoomListAdapter(requireContext()) {chatRoom -> moveChatRoomMessage(chatRoom) } recyclerView.layoutManager = LinearLayoutManager(requireContext()) } fun moveChatRoomMessage(chatRoom: ChatRoom) { val intent = Intent(requireContext(), ChatRoomMessageActivity::class.java) intent.putExtra("name", chatRoom.name) intent.putExtra("idRoom", chatRoom.idRoom) intent.putExtra("idServerLastMessage", chatRoom.idServerLastMessage) intent.putExtra("memberNumber", chatRoom.chatMembers.lastIndex) intent.putExtra("room_id", chatRoom.id) startActivity(intent) } inner class CommunityChatRoomListAdapter(val context: Context, val itemClick: (ChatRoom) -> Unit) : RecyclerView.Adapter<CommunityChatRoomListAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.list_item_main_chat, parent, false) return ViewHolder(view, itemClick) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(realmListChatRooms[position]!!, context) } override fun getItemCount() = realmListChatRooms.size inner class ViewHolder(itemView: View?, itemClick: (ChatRoom) -> Unit) : RecyclerView.ViewHolder(itemView!!) { var llayoutProfile = itemView?.list_item_chat_llayout var ivProfile = itemView?.list_item_chat_iv_profile var ivMultiProfile = itemView?.list_item_chat_iv_multiProfile var ivMultiProfile2 = itemView?.list_item_chat_iv_multiProfile2 var tvTitle = itemView?.list_item_chat_tv_title var tvMember = itemView?.list_item_chat_tv_chatMember var tvContent = itemView?.list_item_chat_tv_content var ivNew = itemView?.list_item_chat_tv_new var tvDate = itemView?.list_item_chat_tv_date fun bind(chatRoom: ChatRoom, context: Context) { try { val chatMembers = chatRoom.chatMembers when (chatMembers.size) { 1 -> { //대화 상대 없음 llayoutProfile?.visibility = View.INVISIBLE ivProfile?.visibility = View.VISIBLE tvMember?.visibility = View.GONE } 2 -> { //대화 상대 1명 ivProfile?.visibility = View.VISIBLE ivMultiProfile?.visibility = View.GONE ivMultiProfile2?.visibility = View.GONE tvMember?.visibility = View.GONE GlideUtil.displayImage(context, OpenriderConstants.AppUrl.Domain() + chatMembers[1]?.profileUrl, ivProfile, GlideUtil.DEFAULT_TYPE_PROFILE_MIDDLE) //상대방 프로필 1장 표시 val seq = preferenceUtilProfile?.seq for (i in 0 until chatMembers.size - 1) { if (chatMembers[i]?.id != seq?.toLong()) { //TODO 상대방 이미지 표시 } } } else -> { //대화 상대 2명 이상 ivProfile?.visibility = View.GONE ivMultiProfile?.visibility = View.VISIBLE ivMultiProfile2?.visibility = View.VISIBLE tvMember?.visibility = View.VISIBLE GlideUtil.displayImage(context, OpenriderConstants.AppUrl.Domain() + chatMembers[1]?.profileUrl, ivMultiProfile, GlideUtil.DEFAULT_TYPE_PROFILE_MIDDLE) GlideUtil.displayImage(context, OpenriderConstants.AppUrl.Domain() + chatMembers[0]?.profileUrl, ivMultiProfile2, GlideUtil.DEFAULT_TYPE_PROFILE_MIDDLE) var memberCnt = chatMembers.size tvMember?.text = "($memberCnt)"
// var index = 0 // val seq = preferenceUtilProfile?.seq // // if (seq!!.isNotEmpty()) { // // try { // // for (i in 0 until memberCnt - 1) { // // if (chatMembers[i]?.idMember != seq.toLong()) { // //TODO arrProfile[Index]에 이미지를 표시하고 index++를 해준다. // index++ // } // } // } catch (e: java.lang.Exception) { // e.printStackTrace() // } // } } }
//채팅방 이름 //정해놓은게 없으면 사용자 닉네임으로. var roomname = "" for(i in 0 until chatMembers.lastIndex) roomname += AesssUtil.decrypt(chatMembers[i]?.nickName) + "," if(chatRoom.name == ""){ tvTitle?.text = roomname.trimEnd(',') //db update realm.beginTransaction() chatRoom.name = roomname.trimEnd(',') realm.commitTransaction() } else{ tvTitle?.text = chatRoom.name } //채팅 내용 tvContent?.text = chatRoom.lastMessageContent // 마지막 채팅 입력 시간 if(chatRoom.lastMessageDateInsert == ""){ // tvDate?.text = chatRoom.dateInsert tvDate?.text = calculateTime(getChatDateTime(chatRoom.dateInsert)) } else{ tvDate?.text = calculateTime(getChatDateTime(chatRoom.lastMessageDateInsert)) } //새로운 메세지 표시 if (chatRoom.idLastMessage < chatRoom.idServerLastMessage) { ivNew?.text = (chatRoom.idServerLastMessage - chatRoom.idLastMessage).toString() ivNew?.visibility = View.VISIBLE } else { ivNew?.visibility = View.INVISIBLE } } catch (e: Exception) { e.printStackTrace() } itemView.setOnClickListener{ itemClick(chatRoom) } } } } fun getChatDateTime (strDate: String): Date { val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") simpleDateFormat.timeZone = TimeZone.getTimeZone("GMT") return simpleDateFormat.parse(strDate) } fun calculateTime(date: Date): String? { val SEC = 60 val MIN = 60 val HOUR = 24 val DAY = 30 val MONTH = 12 val curTime = System.currentTimeMillis() val regTime: Long = date.time var diffTime = (curTime - regTime) / 1000 var msg: String? = null if (diffTime < SEC) { // sec msg = diffTime.toString() + "초전" } else if (SEC.let { diffTime /= it; diffTime } < MIN) { // min println(diffTime) msg = diffTime.toString() + "분전" } else if (MIN.let({ diffTime /= it; diffTime }) < HOUR) { // hour msg = diffTime.toString() + "시간전" } else if (HOUR.let({ diffTime /= it; diffTime }) < DAY) { // day msg = diffTime.toString() + "일전" } else if (DAY.let({ diffTime /= it; diffTime }) < MONTH) { // day msg = diffTime.toString() + "달전" } else { msg = diffTime.toString() + "년전" } return msg } suspend fun JobSelectListChatRoom() = CoroutineScope(Dispatchers.Main).launch { // Show progress from UI thread var resultJSON = JSONObject() CoroutineScope(Dispatchers.Default).async { // background thread try { val requestJSON = JSONObject() val chatService = ChatService(requireContext()) requestJSON.put("memberSeq", preferenceUtilProfile!!.seq) requestJSON.put(RequestParamName.CURRENT_PAGE, nCurrentPage) //채팅방 목록 불러오기 resultJSON = chatService.selectListChatRoom(requestJSON) } catch (e: Exception) { e.printStackTrace() } }.await() try { //결과 확인 if (isAdded) { if (OpenriderUtil.isHasJSONData(resultJSON, ResponseParamName.RESULT) && resultJSON.getBoolean(ResponseParamName.RESULT)) { insertChatRoomListData(resultJSON) } else { getChatRoomListData() } } } catch (e: Exception) { e.printStackTrace() getChatRoomListData() } }
}
https://medium.com/hongbeomi-dev/%EC%BD%94%ED%8B%80%EB%A6%B0%EC%9D%98-%EC%BD%94%EB%A3%A8%ED%8B%B4-3-composing-suspending-functions-8ee5127e4d49
fcm gcm
package kr.co.openit.openrider.service.main.fragment
import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.LinearLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.realm.Realm import io.realm.RealmList import io.realm.Sort import io.realm.kotlin.createObject import io.realm.kotlin.where import kotlinx.android.synthetic.main.fragment_main_chat. import kotlinx.android.synthetic.main.list_item_main_chat.view. import kotlinx.coroutines. import kr.co.openit.openrider.R import kr.co.openit.openrider.common.constants.OpenriderConstants import kr.co.openit.openrider.common.constants.OpenriderConstants.RequestParamName import kr.co.openit.openrider.common.constants.OpenriderConstants.ResponseParamName import kr.co.openit.openrider.common.fragments.BaseFragment import kr.co.openit.openrider.common.preference.PreferenceUtilProfile import kr.co.openit.openrider.common.realm.ChatMember import kr.co.openit.openrider.common.realm.ChatRoom import kr.co.openit.openrider.common.utils.AesssUtil import kr.co.openit.openrider.common.utils.GlideUtil import kr.co.openit.openrider.common.utils.OpenriderUtil import kr.co.openit.openrider.service.chat.activity.ChatRoomCreateActivity import kr.co.openit.openrider.service.chat.activity.ChatRoomMessageActivity import kr.co.openit.openrider.service.chat.service.ChatService import org.json.JSONObject import java.text.SimpleDateFormat import java.util. import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.resume
class MainChatFragment : BaseFragment() {
// if (OpenriderUtil.isHasJSONData(chatRoomJSON, "TITLE")) { // realmQueryChatRoom.name = chatRoomJSON.getString("TITLE") // }
// if (OpenriderUtil.isHasJSONData(chatRoomJSON, "TITLE")) { // chatRoom.name = chatRoomJSON.getString("TITLE") // }
// var index = 0 // val seq = preferenceUtilProfile?.seq // // if (seq!!.isNotEmpty()) { // // try { // // for (i in 0 until memberCnt - 1) { // // if (chatMembers[i]?.idMember != seq.toLong()) { // //TODO arrProfile[Index]에 이미지를 표시하고 index++를 해준다. // index++ // } // } // } catch (e: java.lang.Exception) { // e.printStackTrace() // } // } } }
}