IMServiceImpl.kt 15.4 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
46
import com.yidianling.uikit.custom.widget.expertConsultService.view.ExpertConsultServiceListDialog2
ydl committed
47 48
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
konghaorui committed
49 50 51 52 53 54 55 56

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

57 58
    private var expertConsultServiceListDialog2: ExpertConsultServiceListDialog2 ?= null

konghaorui committed
59 60 61 62
    override fun isHasUnread(): Boolean {
        return MsgReceiveHelper.isHasUnread
    }

konghaorui committed
63 64 65 66 67
    override fun init(context: Context?) {

    }

    override fun startP2PSession(context: Activity, toUid: String) {
刘鹏 committed
68 69

        IMChatUtil.startCms(context as AppCompatActivity, toUid, 0)
konghaorui committed
70 71
    }

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

konghaorui committed
79
    override fun startP2PXiaoYi(context: Context) {
80
        if (!ImIn.loginByOneKeyLogin(context,true)) {
konghaorui committed
81 82
            return
        }
83
        SessionHelper.startP2PSession(context, -1, ImConstants.KEFUXIAOYI, null, P2PCustomActionHandlerImpl("14", "客服小壹", "https://static.ydlcdn.com/mobile/images/avatar_girl_app.png"))
konghaorui committed
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 134 135 136
    }

    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
137 138 139 140 141
        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
142

严久程 committed
143 144 145
            override fun onException(exception: Throwable?) {
                callback.onException(exception)
            }
konghaorui committed
146

严久程 committed
147 148 149 150
            override fun onFailed(code: Int) {
                callback.onFailed(code)
            }
        })
konghaorui committed
151 152 153 154 155
    }

    override fun sendSubscriptionTimeMessage(sessionId: String?, content: String, callback: IMRequestCallback<Void>) {
        val customTime = CustomAttachSubScriptTime(content)
        val message = MessageBuilder.createCustomMessage(sessionId, SessionTypeEnum.P2P, content, customTime)
严久程 committed
156 157 158 159 160
        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
161

严久程 committed
162 163 164
            override fun onException(exception: Throwable?) {
                callback.onException(exception)
            }
konghaorui committed
165

严久程 committed
166 167 168 169
            override fun onFailed(code: Int) {
                callback.onFailed(code)
            }
        })
konghaorui committed
170 171 172 173 174

    }

    override fun showSelector(activity: Activity, requestCode: Int) {
        val option = PickImageHelper.PickImageOption()
konghaorui committed
175
        option.titleResId = R.string.im_input_panel_photo
konghaorui committed
176 177 178 179 180
        option.multiSelect = true
        option.multiSelectMaxCount = 9
        option.crop = false
        option.cropOutputImageWidth = 720
        option.cropOutputImageHeight = 720
严久程 committed
181
        //        option.outputPath = StorageUtil.getWritePath(StringUtils.get32UUID() + ".jpg", StorageType.TYPE_TEMP)
konghaorui committed
182 183 184 185 186
        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
187
        val customAttachmentTest = CustomAttachmentTest(CustomAttachmentTest.FLAG_RESULT, title, head, url, id, share_url)
konghaorui committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        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
212
        IMChatUtil.startChat(context as AppCompatActivity, toUid,0)
konghaorui committed
213
    }
214

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

严久程 committed
220 221 222 223
    override fun startChatCloseReplaceChat(context: Activity, toUid: String) {
        IMChatUtil.startChatCloseReplaceChat(context as AppCompatActivity,toUid)
    }

224 225 226
    override fun getUnReadByUid(uid: String): Int {
        return MsgReceiveHelper.getUnNum(uid)
    }
227 228 229 230

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

    /**
     * 发送自定义通知: 不推送、不计入未读消息
     */
    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
245
        customNotification.isSendToOnlineUserOnly = true
严久程 committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
        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) {
262 263 264 265 266
        ImObserversHelper.getInstance().imCustomNotificationCallBack.add(callback)
    }

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

ydl committed
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 308 309 310
    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
311
        IMChatUtil.startKefuChat(context as AppCompatActivity)
ydl committed
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 386 387 388
    }

    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
389 390 391
            .setCallback(object : RequestCallback<Void?> {
                override fun onSuccess(param: Void?) {
                    MessageListPanelHelper.getInstance().notifyAddMessage(message)
ydl committed
392 393 394 395 396 397 398 399 400 401 402
                    startChat(context, toUid.toString(), 0x001, 0)
                }

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

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

ydl committed
404 405
    }

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

ydl committed
414 415 416
    override fun isWifiOr3G(activity: Activity): Boolean {
        return NetworkUtil.isWifiOr3G(activity)
    }
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

    override fun showConsultServiceDialog(activity: Activity, toUid: String, doctorId: String) {

        // 获取专家是否在繁忙状态
        if (activity != null) {
            expertConsultServiceListDialog2 =
                ExpertConsultServiceListDialog2(
                    activity, null, false, toUid,
                    doctorId
                )
            expertConsultServiceListDialog2?.show()
        }
    }

    override fun dismissConsultServiceDialog() {
        expertConsultServiceListDialog2?.changeItem()
    }
konghaorui committed
434
}