IMServiceImpl.kt 14.7 KB
Newer Older
konghaorui committed
1 2
package com.yidianling.im.modular.service

ydl committed
3
import android.annotation.SuppressLint
konghaorui committed
4
import android.app.Activity
ydl committed
5
import android.app.Application
konghaorui committed
6
import android.content.Context
YKai committed
7
import androidx.appcompat.app.AppCompatActivity
YKai committed
8
import androidx.fragment.app.Fragment
konghaorui committed
9 10 11 12 13 14 15 16
import com.alibaba.android.arouter.facade.annotation.Route
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.LoginInfo
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
严久程 committed
17 18
import com.netease.nimlib.sdk.msg.model.CustomNotification
import com.netease.nimlib.sdk.msg.model.CustomNotificationConfig
konghaorui committed
19 20
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.StringUtils
ydl committed
21
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils
ydl committed
22
import com.yidianling.avchatkit.common.util.NetworkUtil
ydl committed
23
import com.yidianling.common.tools.ToastUtil
konghaorui committed
24
import com.yidianling.im.R
YKai committed
25
import com.yidianling.im.api.bean.*
ydl committed
26
import com.yidianling.im.api.listener.ApiStringResponseCallback
konghaorui committed
27 28
import com.yidianling.im.api.service.IImService
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl
ydl committed
29
import com.yidianling.im.config.NimApplication
30
import com.yidianling.im.config.constants.ImConstants
konghaorui committed
31
import com.yidianling.im.helper.IMChatUtil
严久程 committed
32
import com.yidianling.im.helper.ImObserversHelper
YKai committed
33
import com.yidianling.im.helper.LogoutHelper
konghaorui committed
34
import com.yidianling.im.helper.MsgReceiveHelper
ydl committed
35
import com.yidianling.im.http.ImRetrofitApi
konghaorui committed
36 37 38
import com.yidianling.im.preference.IMCache
import com.yidianling.im.router.ImIn
import com.yidianling.im.session.SessionHelper
ydl committed
39
import com.yidianling.im.session.extension.CustomAttachModifyTime
konghaorui committed
40 41
import com.yidianling.im.session.extension.CustomAttachSubScriptTime
import com.yidianling.im.session.extension.CustomAttachmentTest
ydl committed
42
import com.yidianling.im.ui.page.NewMultiMessageFragment
konghaorui committed
43 44 45
import com.yidianling.nimbase.common.media.picker.PickImageHelper
import com.yidianling.uikit.api.NimUIKit
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper
ydl committed
46 47
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
konghaorui committed
48 49 50 51 52 53 54 55

/**
 * Created by haorui on 2019-12-11 .
 * Des:
 */
@Route(path = "/im/ImService")
class IMServiceImpl : IImService {

konghaorui committed
56 57 58 59
    override fun isHasUnread(): Boolean {
        return MsgReceiveHelper.isHasUnread
    }

konghaorui committed
60 61 62 63 64
    override fun init(context: Context?) {

    }

    override fun startP2PSession(context: Activity, toUid: String) {
刘鹏 committed
65 66

        IMChatUtil.startCms(context as AppCompatActivity, toUid, 0)
konghaorui committed
67 68
    }

69 70 71
    override fun startP2PSession(context: Activity, location: Int, ffrom2: String?) {
        IMChatUtil.startCms(context,location,ffrom2)
    }
72 73 74
    override fun startChatBySessionId(context: Activity, toUid: String) {
        IMChatUtil.startChatBySessionId(context as AppCompatActivity,toUid)
    }
75

konghaorui committed
76
    override fun startP2PXiaoYi(context: Context) {
77
        if (!ImIn.loginByOneKeyLogin(context,true)) {
konghaorui committed
78 79
            return
        }
80
        SessionHelper.startP2PSession(context, -1, ImConstants.KEFUXIAOYI, null, P2PCustomActionHandlerImpl("14", "客服小壹", "https://static.ydlcdn.com/mobile/images/avatar_girl_app.png"))
konghaorui committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    }

    override fun imLogin(info: IMLoginInfo) {
        NimUIKit.setAccount(info.account)
        try {
            NIMClient.getService(AuthService::class.java).login(LoginInfo(info.account, info.passWord))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun login(info: IMLoginInfo, callback: IMRequestCallback<IMLoginInfo>?) {
        NimUIKit.login(LoginInfo(info.account, info.passWord), object : RequestCallback<LoginInfo> {
            override fun onSuccess(param: LoginInfo?) {
                if (param != null) {
                    val newParam = IMLoginInfo(param.account, param.token)
                    callback?.onSuccess(newParam)
                }
            }

            override fun onFailed(code: Int) {
                callback?.onFailed(code)
            }

            override fun onException(exception: Throwable?) {
                callback?.onException(exception)
            }
        })
    }

    override fun setAccount(account: String) {
        NimUIKit.setAccount(account)
    }

    override fun setChattingAccountAll() {
        NIMClient.getService(MsgService::class.java).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_ALL, SessionTypeEnum.None)
    }

    override fun setChattingAccountNone() {
        NIMClient.getService(MsgService::class.java).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None)
    }

    override fun logout() {
        NIMClient.getService(AuthService::class.java).logout()
    }

    override fun clear() {
        NimUIKit.logout()
        IMCache.clear()
    }

    override fun createTextMessage(sessionId: String?, content: String, callback: IMRequestCallback<Void>) {
        val message = MessageBuilder.createTextMessage(sessionId, SessionTypeEnum.P2P, content)
严久程 committed
134 135 136 137 138
        NIMClient.getService(MsgService::class.java).sendMessage(message, false).setCallback(object : RequestCallback<Void> {
            override fun onSuccess(param: Void?) {
                callback.onSuccess(param)
                MessageListPanelHelper.getInstance().notifyAddMessage(message)
            }
konghaorui committed
139

严久程 committed
140 141 142
            override fun onException(exception: Throwable?) {
                callback.onException(exception)
            }
konghaorui committed
143

严久程 committed
144 145 146 147
            override fun onFailed(code: Int) {
                callback.onFailed(code)
            }
        })
konghaorui committed
148 149 150 151 152
    }

    override fun sendSubscriptionTimeMessage(sessionId: String?, content: String, callback: IMRequestCallback<Void>) {
        val customTime = CustomAttachSubScriptTime(content)
        val message = MessageBuilder.createCustomMessage(sessionId, SessionTypeEnum.P2P, content, customTime)
严久程 committed
153 154 155 156 157
        NIMClient.getService(MsgService::class.java).sendMessage(message, false).setCallback(object : RequestCallback<Void> {
            override fun onSuccess(param: Void?) {
                callback.onSuccess(param)
                MessageListPanelHelper.getInstance().notifyAddMessage(message)
            }
konghaorui committed
158

严久程 committed
159 160 161
            override fun onException(exception: Throwable?) {
                callback.onException(exception)
            }
konghaorui committed
162

严久程 committed
163 164 165 166
            override fun onFailed(code: Int) {
                callback.onFailed(code)
            }
        })
konghaorui committed
167 168 169 170 171

    }

    override fun showSelector(activity: Activity, requestCode: Int) {
        val option = PickImageHelper.PickImageOption()
konghaorui committed
172
        option.titleResId = R.string.im_input_panel_photo
konghaorui committed
173 174 175 176 177
        option.multiSelect = true
        option.multiSelectMaxCount = 9
        option.crop = false
        option.cropOutputImageWidth = 720
        option.cropOutputImageHeight = 720
严久程 committed
178
        //        option.outputPath = StorageUtil.getWritePath(StringUtils.get32UUID() + ".jpg", StorageType.TYPE_TEMP)
konghaorui committed
179 180 181 182 183
        option.outputPath = YdlCommonOut.getApp().externalCacheDir.absolutePath + "/" + StringUtils.get32UUID() + ".jpg"
        PickImageHelper.pickImage(activity, requestCode, option)
    }

    override fun sendTestResultMessage(uid: String, content: String, title: String?, head: String?, url: String?, id: Int, share_url: String?, callback: IMRequestCallback<Void>) {
严久程 committed
184
        val customAttachmentTest = CustomAttachmentTest(CustomAttachmentTest.FLAG_RESULT, title, head, url, id, share_url)
konghaorui committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        val message = MessageBuilder.createCustomMessage(uid, SessionTypeEnum.P2P, "测试结果", customAttachmentTest)

        NIMClient.getService(MsgService::class.java).sendMessage(message, false).setCallback(object : RequestCallback<Void> {
            override fun onSuccess(param: Void?) {
                callback.onSuccess(param)
                MessageListPanelHelper.getInstance().notifyAddMessage(message)
            }

            override fun onFailed(code: Int) {
                callback.onFailed(code)
            }

            override fun onException(exception: Throwable?) {
                callback.onException(exception)
            }
        })

    }

    /**
     * 跳转私聊界面
     */
    override fun startChat(context: Activity, toUid: String, flag: Int, canTalk: Int) {
        //这里虽然是倾述流程进入私聊,但不需要发送自定义消息
konghaorui committed
209
        IMChatUtil.startChat(context as AppCompatActivity, toUid,0)
konghaorui committed
210
    }
211

ydl committed
212 213
    override fun startChat(context: Activity, toUid: String, flag: Int, canTalk: Int, isFramQingsu: Int, isFromMessageList: Boolean) {
        //这里虽然是倾述流程进入私聊,但不需要发送自定义消息
konghaorui committed
214
        IMChatUtil.startChat(context as AppCompatActivity, toUid,isFramQingsu)
konghaorui committed
215
    }
216

严久程 committed
217 218 219 220
    override fun startChatCloseReplaceChat(context: Activity, toUid: String) {
        IMChatUtil.startChatCloseReplaceChat(context as AppCompatActivity,toUid)
    }

221 222 223
    override fun getUnReadByUid(uid: String): Int {
        return MsgReceiveHelper.getUnNum(uid)
    }
224 225 226 227

    override fun getAllUnReadNum(): Int {
        return MsgReceiveHelper.getAllUnNum()
    }
严久程 committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241

    /**
     * 发送自定义通知: 不推送、不计入未读消息
     */
    override fun sendCustomNotification(toUid: String, content: String, callback: IMSendCustomNotificationResultCallBack) {
        val config = CustomNotificationConfig()
        config.enablePush = false
        config.enablePushNick = false
        config.enableUnreadCount = false
        val customNotification = CustomNotification()
        customNotification.sessionType = SessionTypeEnum.P2P
        customNotification.sessionId = toUid
        customNotification.config = config
        customNotification.content = content
242
//        customNotification.isSendToOnlineUserOnly=false
严久程 committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        NIMClient.getService(MsgService::class.java).sendCustomNotification(customNotification).setCallback(object : RequestCallback<Void?> {
            override fun onSuccess(param: Void?) {
                callback.onSuccess()
            }

            override fun onFailed(code: Int) {
                callback.onFailed(code)
            }

            override fun onException(exception: Throwable) {
                callback.onException(exception)
            }
        })
    }

    override fun registerObserveCustomNotification(callback: IMRegisterObserverCustomNotificationCallBack) {
259 260 261 262 263
        ImObserversHelper.getInstance().imCustomNotificationCallBack.add(callback)
    }

    override fun unregisterObserveCustomNotification(callback: IMRegisterObserverCustomNotificationCallBack) {
        ImObserversHelper.getInstance().imCustomNotificationCallBack.remove(callback)
严久程 committed
264
    }
265

ydl committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    override fun getMultiMessageFragment(): Fragment {
        return NewMultiMessageFragment()
    }

    override fun nextUnreadItem(fragment: Fragment): Boolean {
        if (fragment is NewMultiMessageFragment) {
            fragment.nextUnReadItem()
            return true
        }
        return false
    }

    override fun isChatFragment(fragment: Fragment): Boolean {
        if (fragment is NewMultiMessageFragment) {
            return true
        }
        return false
    }

    override fun isImLogin(): Boolean {
        return ImIn.isLogin()
    }

    override fun requestTopUnReadNumber(fragment: Fragment) {
        if (fragment is NewMultiMessageFragment) {
            fragment.requestTopUnReadNumber()
        }
    }

    override fun loginIm(uid: String?, hxPwd: String?) {
        ImIn.loginIm(uid?:"", hxPwd?:"")
    }

    override fun logoutAll() {
        LogoutHelper.logout()
    }

    override fun initImCache(mContext: Context) {
        IMCache.setContext(mContext)
    }

    override fun startKefuChat(context: Context, toUid: String, flag: Int, canTalk: Int) {
konghaorui committed
308
        IMChatUtil.startKefuChat(context as AppCompatActivity)
ydl committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    }

    override fun startP2PSession(mContext: Context, userType: Int, account: String, toChatUsername: String, toName: String, head: String) {
        SessionHelper.startP2PSession(mContext, userType, account, null,
            P2PCustomActionHandlerImpl(toChatUsername, toName, head))
    }

    override fun updateUserHead(head: String?) {
        ImIn.updateUserHead(head?:"")
    }

    override fun updateUserName(name: String?) {
        ImIn.updateUserName(name?:"")
    }

    override fun imInSetRing(bool: Boolean) {
        ImIn.setRing(bool)
    }

    override fun imInSetVibrate(bool: Boolean) {
        ImIn.setVibrate(bool)
    }

    override fun getUserInfoDescription(): String? {
        return ImIn.getUserInfo()!!.description
    }

    override fun getEarModeCloseType(): String {
        return NimApplication.EAR_MODE_CLOSE
    }

    override fun getEarModeKey(): String {
        return NimApplication.EAR_MODE_KEY
    }

    override fun getEarModeOpenType(): String {
        return NimApplication.EAR_MODE_OPEN
    }

    override fun getEarModeIsOpen(): Boolean {
        return ImIn.getEarModeIsOpen()
    }

    override fun updateEarMode(bool: Boolean) {
        ImIn.updateEarMode(bool)
    }

    @SuppressLint("CheckResult")
    override fun getChatUid(context: Context?, uid: String, callback: ApiStringResponseCallback) {
        ImRetrofitApi.getImJavaApi().getChatUid(uid)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                callback.onUidCallback(resp.data.getChatUid())

            }, { t ->
                context?.let {
                    HttpErrorUtils.handleError(context, t)
                }
            })
    }

    override fun chatScheule(context: Activity, userUrl: String, docUrl: String, dsmId: Int, title: String, toUid: Int) {
        val customAttachModifyTime = CustomAttachModifyTime(
            userUrl,
            docUrl,
            dsmId,
            title
        )

        val message = MessageBuilder.createCustomMessage(
            toUid.toString(),
            SessionTypeEnum.P2P,
            customAttachModifyTime
        )

        NIMClient.getService(MsgService::class.java).sendMessage(message, false)
YKai committed
386 387 388
            .setCallback(object : RequestCallback<Void?> {
                override fun onSuccess(param: Void?) {
                    MessageListPanelHelper.getInstance().notifyAddMessage(message)
ydl committed
389 390 391 392 393 394 395 396 397 398 399
                    startChat(context, toUid.toString(), 0x001, 0)
                }

                override fun onFailed(code: Int) {
                    ToastUtil.toastShort("加载失败")
                }

                override fun onException(exception: Throwable) {
                    ToastUtil.toastShort("加载失败")
                }
            })
YKai committed
400

ydl committed
401 402
    }

403 404 405 406 407
    override fun initIm(
        app: Application,
        activity: Class<out Activity>,
        imInitBean: IMInitConfigBean
    ) {
408
        NimApplication.getInstance().initIm(app, activity, imInitBean)
409 410
    }

ydl committed
411 412 413
    override fun isWifiOr3G(activity: Activity): Boolean {
        return NetworkUtil.isWifiOr3G(activity)
    }
konghaorui committed
414
}