IMServiceImpl.kt 14.5 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
42
import com.yidianling.im.ui.activity.CmsExamQuestionPaperActivity
ydl committed
43
import com.yidianling.im.ui.page.NewMultiMessageFragment
konghaorui committed
44 45 46
import com.yidianling.nimbase.common.media.picker.PickImageHelper
import com.yidianling.uikit.api.NimUIKit
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper
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 {

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

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

    }

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

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

70 71 72 73
    override fun startP2PSession(context: Activity, location: Int, ffrom2: String?) {
        IMChatUtil.startCms(context,location,ffrom2)
    }

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

    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
132 133 134 135 136
        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
137

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

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

    override fun sendSubscriptionTimeMessage(sessionId: String?, content: String, callback: IMRequestCallback<Void>) {
        val customTime = CustomAttachSubScriptTime(content)
        val message = MessageBuilder.createCustomMessage(sessionId, SessionTypeEnum.P2P, content, customTime)
严久程 committed
151 152 153 154 155
        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
156

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

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

    }

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

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

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

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

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

    /**
     * 发送自定义通知: 不推送、不计入未读消息
     */
    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
240
//        customNotification.isSendToOnlineUserOnly=false
严久程 committed
241 242 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) {
        ImObserversHelper.getInstance().imCustomNotificationCallBack=callback
    }
259

ydl committed
260 261 262 263 264 265 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
    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
302
        IMChatUtil.startKefuChat(context as AppCompatActivity)
ydl committed
303 304 305
    }

    override fun startP2PSession(mContext: Context, userType: Int, account: String, toChatUsername: String, toName: String, head: String) {
刘鹏 committed
306
        SessionHelper.startP2PSession(mContext, 3, account, null,
ydl committed
307 308 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
            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
380 381 382
            .setCallback(object : RequestCallback<Void?> {
                override fun onSuccess(param: Void?) {
                    MessageListPanelHelper.getInstance().notifyAddMessage(message)
ydl committed
383 384 385 386 387 388 389 390 391 392 393
                    startChat(context, toUid.toString(), 0x001, 0)
                }

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

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

ydl committed
395 396 397 398 399
    }

    override fun initIm(app: Application, activity: Class<out Activity>) {
        NimApplication.getInstance().initIm(app, activity)
    }
ydl committed
400

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

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