ImObserversHelper.kt 9.94 KB
Newer Older
konghaorui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package com.yidianling.im.helper

import android.util.Log
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.Observer
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.StatusCode
import com.netease.nimlib.sdk.auth.AuthServiceObserver
import com.netease.nimlib.sdk.avchat.model.AVChatAttachment
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.MsgServiceObserve
import com.netease.nimlib.sdk.msg.constant.AttachStatusEnum
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum
严久程 committed
15
import com.netease.nimlib.sdk.msg.model.CustomNotification
konghaorui committed
16 17 18 19
import com.netease.nimlib.sdk.msg.model.IMMessage
import com.netease.nimlib.sdk.msg.model.RevokeMsgNotification
import com.netease.nimlib.sdk.team.TeamServiceObserver
import com.netease.nimlib.sdk.team.model.Team
严久程 committed
20 21
import com.ydl.ydlcommon.utils.LogUtil
import com.yidianling.im.api.bean.IMRegisterObserverCustomNotificationCallBack
konghaorui committed
22
import com.yidianling.im.api.event.AccountChangeEvent
ydl committed
23
import com.yidianling.im.api.event.MsgPushEvent
konghaorui committed
24
import com.yidianling.im.event.TeamRemoveEvent
konghaorui committed
25 26 27 28 29 30 31 32 33 34 35 36
import com.yidianling.im.preference.IMCache
import com.yidianling.im.preference.ImTempData
import com.yidianling.im.session.extension.CustomAttachReceivedMoney
import com.yidianling.im.session.extension.CustomAttachRedPacket
import com.yidianling.im.session.extension.CustomAttachmentReceivedSuccess
import com.yidianling.nimbase.api.model.session.MsgForwardFilter
import com.yidianling.nimbase.api.model.session.MsgRevokeFilter
import com.yidianling.uikit.api.NimUIKit
import com.yidianling.uikit.api.wrapper.NimMessageRevokeObserver
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper
import com.yidianling.uikit.business.team.helper.TeamMemberAitHelper
import de.greenrobot.event.EventBus
严久程 committed
37
import java.util.concurrent.Executors
konghaorui committed
38 39 40 41 42 43

/**
 * Created by haorui on 2019/5/17.
 * Des:
 */
class ImObserversHelper {
严久程 committed
44
    var imCustomNotificationCallBack: IMRegisterObserverCustomNotificationCallBack? = null
45
        set(value) {
严久程 committed
46 47
            field = value
        }
konghaorui committed
48 49 50 51 52 53 54

    companion object {
        fun getInstance(): ImObserversHelper {
            return Holder.INSTANCE
        }
    }

严久程 committed
55

konghaorui committed
56 57 58 59
    private object Holder {
        val INSTANCE = ImObserversHelper()
    }

严久程 committed
60

konghaorui committed
61 62
    fun registerObserver(register: Boolean) {
        //注册`在线状态变化`观察者
严久程 committed
63
        NIMClient.getService(AuthServiceObserver::class.java).observeOnlineStatus(userStatusObserver, register)
konghaorui committed
64
        //注册`消息撤回`观察者
严久程 committed
65
        NIMClient.getService(MsgServiceObserve::class.java).observeRevokeMessage(messageRevokeObserver, register)
konghaorui committed
66
        //注册`消息接收`观察者
严久程 committed
67
        NIMClient.getService(MsgServiceObserve::class.java).observeReceiveMessage(incomingMessageObserver, register)
konghaorui committed
68
        //注册`移出群`观察者通知
严久程 committed
69 70
        NIMClient.getService(TeamServiceObserver::class.java).observeTeamRemove(teamObserver, register)
        NIMClient.getService(MsgServiceObserve::class.java).observeCustomNotification(receiveSystemMessageObserver, register)
konghaorui committed
71 72
        //注册`未读消息改变数量`观察者
        registerMsgUnreadInfoObserver(register)
严久程 committed
73
        if (register) {
konghaorui committed
74 75 76 77 78 79 80 81 82 83 84
            //注册`消息转发`过滤器
            NimUIKit.setMsgForwardFilter(msgForwardFilter)
            //注册`消息撤回`过滤器
            NimUIKit.setMsgRevokeFilter(msgRevokeFilter)
        }
    }

    private fun registerMsgUnreadInfoObserver(register: Boolean) {
        if (register) {
            ReminderManager.getInstance().registerUnreadNumChangedCallback(unreadNumChangedCallback)
        } else {
严久程 committed
85
            ReminderManager.getInstance().unregisterUnreadNumChangedCallback(unreadNumChangedCallback)
konghaorui committed
86 87 88
        }
    }

严久程 committed
89 90 91
    private var unreadNumChangedCallback: ReminderManager.UnreadNumChangedCallback = ReminderManager.UnreadNumChangedCallback() {
        MsgReceiveHelper.onMessageReceived()
    }
konghaorui committed
92 93 94 95 96 97 98 99 100

    private var userStatusObserver: Observer<StatusCode> = Observer { code ->
        if (code.wontAutoLoginForever()) {
            EventBus.getDefault().post(AccountChangeEvent(1))
        }
    }

    private var messageRevokeObserver: Observer<RevokeMsgNotification> = NimMessageRevokeObserver()

严久程 committed
101
    private var teamObserver: Observer<Team> = Observer<Team> { t ->
严久程 committed
102
        EventBus.getDefault().post(TeamRemoveEvent(1, t.id))
严久程 committed
103
    }
konghaorui committed
104 105 106 107 108 109 110

    private var incomingMessageObserver = Observer<List<IMMessage>> { messages ->
        // 处理新收到的消息,为了上传处理方便,SDK 保证参数 messages 全部来自同一个聊天对象。
        Log.e("hzs", "消息接收观察者-----------mainActivity")
        if (messages == null || messages.isEmpty()) {
            return@Observer
        }
严久程 committed
111
        if (messages.size > 1) {
konghaorui committed
112
            //漫游消息 nothing
严久程 committed
113
        } else {
konghaorui committed
114 115 116 117 118 119 120 121 122 123 124 125 126
            //单/群聊消息
            for (m in messages) {
                //监听在线消息中是否有@我
                if (TeamMemberAitHelper.isAitMessage(m)) {
                    //缓存@消息
                    ImTempData.getInstance().addAitMsg(m)
                }
                if (CustomAttachmentReceivedSuccess::class.java.isInstance(m.getAttachment())) {
                    //如果是收款提醒消息  则更新历史收款消息的状态
                    //收款成功
                    flushReceivedMoney(m)
                } else {
                    MsgReceiveHelper.onMessageReceived()
严久程 committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

                    if (System.currentTimeMillis() - m.time <= 5000) {
                        Executors.newSingleThreadExecutor().execute {
                            val userInfo = NimUIKit.getUserInfoProvider().getUserInfo(m.fromAccount)
                            val event = MsgPushEvent()
                            event.toUid = m.fromAccount
                            when (m.msgType) {
                                MsgTypeEnum.text -> {
                                    event.content = m.content
                                }
                                MsgTypeEnum.image -> {
                                    event.content = "[图片]"
                                }
                                MsgTypeEnum.audio -> {
                                    event.content = "[语音]"
                                }
                                MsgTypeEnum.video -> {
                                    event.content = "[视频]"
                                }
                                else -> {
                                    event.content = "[链接]"
                                }
                            }
                            if (userInfo != null) {
                                event.name = userInfo.name
                                event.headUrl = userInfo.avatar
                            }

严久程 committed
155
                            //                            LogUtil.e("发送事件:$event")
严久程 committed
156 157 158
                            EventBus.getDefault().post(event)
                        }
                    }
konghaorui committed
159 160 161 162 163
                }
            }
        }
    }

严久程 committed
164
    private var msgForwardFilter = MsgForwardFilter { message ->
konghaorui committed
165 166 167 168 169 170 171 172 173 174
        if (message.direct == MsgDirectionEnum.In && (message.attachStatus == AttachStatusEnum.transferring || message.attachStatus == AttachStatusEnum.fail)) {
            // 接收到的消息,附件没有下载成功,不允许转发
            return@MsgForwardFilter true
        } else if (message.msgType == MsgTypeEnum.custom && message.attachment != null) {
            // 白板消息和阅后即焚消息 不允许转发
            return@MsgForwardFilter true
        }
        false
    }

严久程 committed
175 176
    private var receiveSystemMessageObserver: Observer<CustomNotification> = Observer<CustomNotification> {
        LogUtil.e(it.content)
177
        imCustomNotificationCallBack?.onObserverCustomNotification(it.fromAccount, it.sessionId, it.content)
严久程 committed
178
    }
konghaorui committed
179 180

    private var msgRevokeFilter = MsgRevokeFilter { message ->
严久程 committed
181
        if (message.attachment != null && message.attachment is AVChatAttachment && message.attachment is CustomAttachRedPacket) {
konghaorui committed
182 183 184 185 186 187 188 189 190 191 192 193
            // 视频通话消息和白板消息 不允许撤回
            return@MsgRevokeFilter true
        } else if (IMCache.getAccount() != null && IMCache.getAccount() == message.sessionId) {
            // 发给我的电脑 不允许撤回
            return@MsgRevokeFilter true
        }
        false
    }

    //如果是收款提醒消息  则更新历史收款消息的状态
    fun flushReceivedMoney(m: IMMessage) {
        //跟新收款消息
严久程 committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        NIMClient.getService(MsgService::class.java).queryMessageListByType(MsgTypeEnum.custom, m, 100).setCallback(object : RequestCallback<List<IMMessage>> {
            override fun onSuccess(imMessages: List<IMMessage>) {
                for (im in imMessages) {
                    if (im.attachment is CustomAttachReceivedMoney) {
                        val money = im.attachment as CustomAttachReceivedMoney

                        if (money.orPay == 1) return
                        val status = m.attachment as CustomAttachmentReceivedSuccess
                        if (money.orderId == null || status.orderid == null) return
                        if (money.orderId == status.orderid) {

                            money.orPay = 1 //设置为已支付
                            im.attachment = money
                            //更新此消息到sdk
                            NIMClient.getService(MsgService::class.java).updateIMMessageStatus(im)
                            //更新私聊界面聊天信息
                            MessageListPanelHelper.getInstance().notifyModifyMessage(im)
                            return
konghaorui committed
212 213 214
                        }
                    }
                }
严久程 committed
215
            }
konghaorui committed
216

严久程 committed
217 218 219
            override fun onFailed(i: Int) {
                //                Log.e("hzs","跟新收款消息失败");
            }
konghaorui committed
220

严久程 committed
221 222 223 224
            override fun onException(throwable: Throwable) {
                //                Log.e("hzs","跟新收款消息异常:"+throwable);
            }
        })
konghaorui committed
225 226
    }
}