添加音视频发送信息

This commit is contained in:
bobobobo
2026-02-09 02:10:27 +08:00
parent bed88896f8
commit eb57bfb6b4
8 changed files with 1147 additions and 901 deletions

View File

@@ -1,102 +1,112 @@
<script setup lang="ts">
import ToolbarItemContainer from '../toolbar-item-container/index.vue'
import custom from '../../../../assets/icon/telephone-icon.svg'
import videoIcon from '../../../../assets/icon/video-icon.svg'
import { isUniFrameWork } from '../../../../utils/env'
import { computed, ref } from 'vue'
import { type IConversationModel } from '@tencentcloud/chat-uikit-engine-lite'
import { navigateTo } from '../../../../../utils/router'
import TUIChatEngine, {
TUIConversationService,
TUIFriendService,
TUIChatService
} from '@tencentcloud/chat-uikit-engine-lite'
import ToolbarItemContainer from '../toolbar-item-container/index.vue'
import custom from '../../../../assets/icon/telephone-icon.svg'
import videoIcon from '../../../../assets/icon/video-icon.svg'
import { isUniFrameWork } from '../../../../utils/env'
import { computed, ref } from 'vue'
import { type IConversationModel } from '@tencentcloud/chat-uikit-engine-lite'
import { navigateTo } from '../../../../../utils/router'
import TUIChatEngine, {
TUIConversationService,
TUIFriendService,
TUIChatService
} from '@tencentcloud/chat-uikit-engine-lite'
import { useUserStore } from '../../../../../stores/user'
const props = withDefaults(
defineProps<{
/** 通话状态: 0 语音 1 视频 */
type ?: '0' | '1'
/** 信息数据 */
currentConversation ?: IConversationModel
}>(),
{
type: '0',
currentConversation: () => ({} as IConversationModel)
}
)
const props = withDefaults(
defineProps<{
/** 通话状态: 0 语音 1 视频 */
type?: '0' | '1'
/** 信息数据 */
currentConversation?: IConversationModel
}>(),
{
type: '0',
currentConversation: () => ({} as IConversationModel)
}
)
/** 语音通话状态 */
const isType = computed(() => props.type === '0')
const { updateCallMode } = useUserStore()
const evaluateIcon = isType.value ? custom : videoIcon
/** 语音通话状态 */
const isType = computed(() => props.type === '0')
const emits = defineEmits(['onDialogPopupShowOrHide'])
const evaluateIcon = isType.value ? custom : videoIcon
const container = ref()
const closeDialog = () => {
container?.value?.toggleDialogDisplay(false)
}
const emits = defineEmits(['onDialogPopupShowOrHide'])
const container = ref()
const closeDialog = () => {
container?.value?.toggleDialogDisplay(false)
}
const onDialogShow = () => {
console.log('弹出窗口', props.currentConversation)
const data = props.currentConversation.userProfile
emits('onDialogPopupShowOrHide', true)
const onDialogShow = () => {
console.log('弹出窗口', props.currentConversation)
const data = props.currentConversation.userProfile
emits('onDialogPopupShowOrHide', false)
if (isType.value) {
let params = {
to: props.currentConversation.conversationID,
conversationType: TUIChatEngine.TYPES.CONV_C2C,
payload: {
text: "拨打语音"
}
}
console.log('params: ', params);
// TUIChatService.sendTextMessage(params)
navigateTo('/pages/room/incom', {
type: 'call',
userID: data.userID,
mediaType: 'audio',
callType: 'out',
})
} else {
let params = {
to: props.currentConversation.conversationID,
conversationType: TUIChatEngine.TYPES.CONV_C2C,
payload: {
text: "拨打视频"
}
}
// TUIChatService.sendTextMessage(params)
uni.setStorageSync('room-parameters', {
callType: 'out',
mediaType: 'video',
targetId: data.userID,
callSelect: 'single',
});
navigateTo('/pages/room/room')
}
}
if (isType.value) {
let params = {
to: props.currentConversation.conversationID,
conversationType: TUIChatEngine.TYPES.CONV_C2C,
payload: {
text: '拨打语音'
}
}
updateCallMode('0')
console.log('params: ', params)
// TUIChatService.sendTextMessage(params)
navigateTo('/pages/room/incom', {
type: 'call',
userID: data.userID,
mediaType: 'audio',
callType: 'out'
})
} else {
let params = {
to: props.currentConversation.conversationID,
conversationType: TUIChatEngine.TYPES.CONV_C2C,
payload: {
text: '拨打视频'
}
}
// TUIChatService.sendTextMessage(params)
uni.setStorageSync('room-parameters', {
callType: 'out',
mediaType: 'video',
targetId: data.userID,
callSelect: 'single'
})
updateCallMode('1')
navigateTo('/pages/room/room')
}
}
const onDialogClose = () => {
console.log('关闭窗口')
emits('onDialogPopupShowOrHide', false)
}
const onDialogClose = () => {
console.log('关闭窗口')
emits('onDialogPopupShowOrHide', false)
}
const onDial = () => {
const data = props.currentConversation.userProfile
// data.userID
// CallLib.enableMicrophone(true)
// CallLib.startSingleCall(data.userID, 0, '邀请您进行语音通话')
}
const onDial = () => {
const data = props.currentConversation.userProfile
// data.userID
// CallLib.enableMicrophone(true)
// CallLib.startSingleCall(data.userID, 0, '邀请您进行语音通话')
}
</script>
<template>
<!-- needBottomPopup -->
<ToolbarItemContainer ref="container" :iconFile="evaluateIcon" :iconWidth="isUniFrameWork ? '34px' : '20px'"
:iconHeight="isUniFrameWork ? '34px' : '20px'" :title="isType ? '语音通话' : '视频通话'" @onDialogShow="onDialogShow"
@onDialogClose="onDialogClose">
<!-- <view class="box-index">
<!-- needBottomPopup -->
<ToolbarItemContainer
ref="container"
:iconFile="evaluateIcon"
:iconWidth="isUniFrameWork ? '34px' : '20px'"
:iconHeight="isUniFrameWork ? '34px' : '20px'"
:title="isType ? '语音通话' : '视频通话'"
@onDialogShow="onDialogShow"
@onDialogClose="onDialogClose"
>
<!-- <view class="box-index">
<view class="top-icon">
<uni-icons
type="back"
@@ -130,7 +140,7 @@
挂点
</button>
</view> -->
</ToolbarItemContainer>
</ToolbarItemContainer>
</template>
<style scoped lang="scss" src="./style/index.scss"></style>
<style scoped lang="scss" src="./style/index.scss"></style>

View File

@@ -151,6 +151,25 @@
</view>
</view>
</template>
<!-- 音视频通话 -->
<template
v-else-if="
customData.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL ||
customData.businessID === CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL
"
>
<view class="call-box" @click="onCall">
<text class="call-text">{{ goodsData.title }}</text>
<uni-icons
:type="
customData.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
? 'phone'
: 'videocam'
"
size="30rpx"
></uni-icons>
</view>
</template>
<template v-else>
<span v-html="content.custom" />
</template>
@@ -165,7 +184,7 @@
computed,
reactive
} from '../../../../adapter-vue'
import {
import TUIChatEngine, {
TUITranslateService,
IMessageModel
} from '@tencentcloud/chat-uikit-engine-lite'
@@ -177,6 +196,7 @@
import unopenedEnvelope from '../../../../assets/icon/unopened-envelope.svg'
import kaiEnvelope from '../../../../assets/icon/kai-unopened-envelope.svg'
import { navigateTo } from '../../../../../utils/router'
import { useUserStore } from '../../../../../stores/user'
interface Props {
messageItem: IMessageModel
@@ -187,6 +207,8 @@
(key: 'claim'): void
}
const { updateCallMode } = useUserStore()
const emits = defineEmits<IEmit>()
const props = withDefaults(defineProps<Props>(), {
@@ -230,6 +252,32 @@
return JSON.parse(props.messageItem.payload.data)
})
/** 点击拨打音视频电话 */
const onCall = () => {
if (props.messageItem.flow === 'out') {
if (
goodsData.value.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
) {
updateCallMode('0')
navigateTo('/pages/room/incom', {
type: 'call',
userID: goodsData.value.userID,
mediaType: 'audio',
callType: 'out'
})
} else {
uni.setStorageSync('room-parameters', {
callType: 'out',
mediaType: 'video',
targetId: goodsData.value.userID,
callSelect: 'single'
})
updateCallMode('1')
navigateTo('/pages/room/room')
}
}
}
/** 点击商品详情 */
const onGoods = () => {
navigateTo('/pages/mall/detail', { productId: goodsData.value.id })
@@ -467,4 +515,12 @@
}
}
}
.call-box {
display: flex;
align-items: center;
.call-text {
margin-right: 10rpx;
}
}
</style>

View File

@@ -404,6 +404,20 @@
return `[直播信息]:${data.title}`
}
}
if (data.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL) {
if (isText) {
return `${text[0]}:[语音通话]`
} else {
return `[语音通话]`
}
}
if (data.businessID === CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL) {
if (isText) {
return `${text[0]}:[视频通话]`
} else {
return `[视频通话]`
}
}
if (data.content === 'Create Group' && item.type === 'GROUP') {
return `${item.getLastMessage('text')?.split(':')[0]}:创建群聊`
}

View File

@@ -23,7 +23,11 @@ export const CHAT_MSG_CUSTOM_TYPE = {
/** 商品详情 */
GOODS: "goods",
/** 直播 */
LIVE: "live"
LIVE: "live",
/** 语音通话 */
VOICE_CALL: "voiceCall",
/** 视频通话 */
VIDEO_CALL: "videoCall",
};
export const DIALOG_CONTENT = {

View File

@@ -11,6 +11,9 @@ export const useAuthUser = () => {
// 响应式状态state & getters
const {
callMode,
callUserId,
callDuration,
imEngine,
userInfo,
tencentUserSig,
@@ -20,6 +23,9 @@ export const useAuthUser = () => {
const { token } = storeToRefs(tokenStore)
return {
callMode,
callUserId,
callDuration,
imEngine,
integralData,
userInfo,

View File

@@ -1,472 +1,527 @@
<template>
<!-- 来电接听界面 -->
<view class="incoming-call">
<!-- 背景模糊层 -->
<view class="blur-background" v-if="callBackground">
<image :src="callBackground" mode="aspectFill" class="bg-image"></image>
<view class="bg-overlay"></view>
</view>
<!-- 顶部栏 -->
<view class="top-bar">
<view class="top-left">
<!-- 通话时间显示 -->
<view v-if="callState === 'dialogue'" class="call-time-container">
<uni-icons type="sound" size="16" color="#fff"></uni-icons>
<text class="call-time">{{ formattedTime }}</text>
</view>
</view>
</view>
<!-- 主内容区 -->
<view class="caller-info">
<view class="caller-avatar-container">
<view class="caller-avatar" :class="{ 'avatar-ring': isRinging }">
<image v-if="callerInfo?.avatar" :src="callerInfo?.avatar" class="avatar-image"></image>
<uni-icons v-else type="contact-filled" size="50" color="#fff"></uni-icons>
</view>
</view>
<text class="caller-name">
{{ callerInfo?.nick || callerInfo?.userID }}
</text>
<text class="call-type">
{{ callState === 'call' ? '呼叫中,等待对方接受邀请...' : callState === 'answer' ? '等待接听...' : '对话中...' }}
</text>
<text class="call-status">{{ mediaType === 'audio' ? "语音通话" : "视频通话" }}</text>
</view>
<!-- 控制按钮 -->
<view class="incoming-controls">
<!-- 麦克风控制按钮仅在通话中显示 -->
<view v-if="callState === 'dialogue'" class="incoming-control" @click="toggleMicrophone">
<view class="call-btn mic-btn" :class="{ 'btn-active': activeBtn === 'mic', 'mic-muted': isMicMuted }">
<uni-icons v-if="!isMicMuted" type="mic" size="28" color="#fff"></uni-icons>
<uni-icons v-else type="micoff" size="28" color="#fff"></uni-icons>
</view>
<text class="btn-text">{{ isMicMuted ? '开启' : '静音' }}</text>
</view>
<!-- 挂断/拒绝按钮 -->
<view class="incoming-control" @click="cutFn(false)">
<view class="call-btn decline-btn" :class="{ 'btn-active': activeBtn === 'decline' }">
<uni-icons type="closeempty" size="32" color="#fff"></uni-icons>
</view>
<text class="btn-text">{{ callState === 'call' || callState == 'dialogue' ? "挂断" : "拒绝" }}</text>
</view>
<!-- 接听按钮 -->
<view v-if="callState === 'answer'" class="incoming-control" @click="cutFn(true)">
<view class="call-btn accept-btn" :class="{ 'btn-active': activeBtn === 'accept' }">
<uni-icons type="checkmarkempty" size="28" color="#fff"></uni-icons>
</view>
<text class="btn-text">接听</text>
</view>
<!-- 扬声器控制按钮仅在通话中显示 -->
<view v-if="callState === 'dialogue'" class="incoming-control" @click="toggleSpeaker">
<view class="call-btn speaker-btn" :class="{ 'btn-active': activeBtn === 'speaker', 'speaker-on': isSpeakerOn }">
<uni-icons v-if="!isSpeakerOn" type="sound" size="28" color="#fff"></uni-icons>
<uni-icons v-else type="sound-filled" size="28" color="#fff"></uni-icons>
</view>
<text class="btn-text">扬声器</text>
</view>
</view>
</view>
</template>
<script setup>
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import {
ref,
watch,
onUnmounted
} from 'vue'
import {
onLoad,
onUnload,
onHide
} from '@dcloudio/uni-app'
import {
TUIUserService
} from '@tencentcloud/chat-uikit-engine-lite'
import {
useUI
} from '../../utils/use-ui'
import {
navigateBack
} from '../../utils/router'
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import { ref, computed, onUnmounted } from 'vue'
import { onLoad, onUnload, onHide } from '@dcloudio/uni-app'
import { TUIUserService } from '@tencentcloud/chat-uikit-engine-lite'
import { useUI } from '../../utils/use-ui'
import { useAuthUser } from '../../composables/useAuthUser'
import { useUserStore } from '../../stores/user'
const { callUserId, callDuration } = useAuthUser()
const { startTimer, stopTimer } = useUserStore()
const { showLoading, hideLoading } = useUI()
const callBackground = ref('/static/images/public/random2.png')
/** 呼叫用户信息 */
const callerInfo = ref({})
/** 通话状态 */
const isRinging = ref(true)
/** 控制按钮状态 */
const activeBtn = ref(null)
/** 麦克风是否静音 */
const isMicMuted = ref(false)
/** 扬声器是否开启 */
const isSpeakerOn = ref(false)
/** 通话计时器 */
const timer = ref(null)
/** 通话时长(秒) */
// const callDuration = ref(0)
/** 好友ID */
const friendID = ref('')
const {
showLoading,
hideLoading
} = useUI()
const callBackground = ref('/static/images/public/random2.png')
/** 呼叫用户信息 */
const callerInfo = ref({})
/** 通话状态 */
const isRinging = ref(true)
/** 控制按钮状态 */
const activeBtn = ref(null)
/** 麦克风是否静音 */
const isMicMuted = ref(false)
/** 扬声器是否开启 */
const isSpeakerOn = ref(false)
/** 通话计时器 */
const timer = ref(null)
/** 通话时长(秒) */
const callDuration = ref(0)
/** 格式化后的时间 */
const formattedTime = ref('00:00')
/**
* 拨打状态
* call: 发起呼叫
* answer: 接听
* dialogue: 对话中
*/
const callState = ref('')
CallLib.onRemoteUserJoined(res => {
console.log(
'Engine:OnRemoteUserJoined=>' +
'主叫端拨出电话被叫端收到请求后加入通话被叫端Id为=>',
res.data.userId
)
callState.value = 'dialogue'
// 开始计时
startTimer()
})
/**
* 拨打状态
* call: 发起呼叫
* answer: 接听
* dialogue: 对话中
*/
const callState = ref('')
CallLib.onRemoteUserJoined(res => {
console.log(
'Engine:OnRemoteUserJoined=>' +
'主叫端拨出电话被叫端收到请求后加入通话被叫端Id为=>',
res.data.userId
)
callState.value = 'dialogue'
// 开始计时
startTimer()
})
// CallLib.onRemoteUserRinging(res => {
// console.log(
// '主叫端拨出电话被叫端收到请求发出振铃响应时触发对端Id为=>',
// res.data.userId
// )
// })
// CallLib.onRemoteUserRinging(res => {
// console.log(
// '主叫端拨出电话被叫端收到请求发出振铃响应时触发对端Id为=>',
// res.data.userId
// )
// })
// CallLib.onError(res => {
// console.log('通话过程中,发生异常,异常原因=>', res.data.reason)
// })
// CallLib.onError(res => {
// console.log('通话过程中,发生异常,异常原因=>', res.data.reason)
// })
/** 格式化时间显示 */
const formattedTime = computed(() => {
const minutes = Math.floor(callDuration.value / 60)
const seconds = callDuration.value % 60
return `${minutes.toString().padStart(2, '0')}:${seconds
.toString()
.padStart(2, '0')}`
})
/** 开始通话计时 */
const startTimer = () => {
stopTimer() // 先停止之前的计时器
timer.value = setInterval(() => {
callDuration.value++
formatTime()
}, 1000)
}
/** 切换麦克风状态 */
const toggleMicrophone = () => {
isMicMuted.value = !isMicMuted.value
// 调用融云SDK的麦克风控制
CallLib.enableMicrophone(!isMicMuted.value)
activeBtn.value = 'mic'
setTimeout(() => (activeBtn.value = null), 200)
}
/** 停止通话计时 */
const stopTimer = () => {
if (timer.value) {
clearInterval(timer.value)
timer.value = null
}
}
/** 切换扬声器状态 */
const toggleSpeaker = () => {
isSpeakerOn.value = !isSpeakerOn.value
// 调用融云SDK的扬声器控制
CallLib.enableSpeaker(isSpeakerOn.value)
activeBtn.value = 'speaker'
setTimeout(() => (activeBtn.value = null), 200)
}
/** 格式化时间显示 */
const formatTime = () => {
const minutes = Math.floor(callDuration.value / 60)
const seconds = callDuration.value % 60
formattedTime.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
/**
* 按钮状态
* @param show true: 接听电话 false: 拒接/挂断电话
*/
const cutFn = show => {
if (show) {
// 接听电话 dialogue
if (mediaType.value === 'audio') {
CallLib.enableMicrophone(true)
}
CallLib.accept()
callState.value = 'dialogue'
// 开始计时
startTimer()
if (mediaType.value === 'video') {
uni.redirectTo({
url: '/pages/room/room'
})
}
} else {
// 停止计时
stopTimer()
// 取消接听,返回上一页
CallLib.hangup()
}
}
/** 切换麦克风状态 */
const toggleMicrophone = () => {
isMicMuted.value = !isMicMuted.value
// 调用融云SDK的麦克风控制
CallLib.enableMicrophone(!isMicMuted.value)
activeBtn.value = 'mic'
setTimeout(() => activeBtn.value = null, 200)
}
const mediaType = ref('audio')
/** 切换扬声器状态 */
const toggleSpeaker = () => {
isSpeakerOn.value = !isSpeakerOn.value
// 调用融云SDK的扬声器控制
CallLib.enableSpeaker(isSpeakerOn.value)
activeBtn.value = 'speaker'
setTimeout(() => activeBtn.value = null, 200)
}
onLoad(async e => {
callState.value = e.type
mediaType.value = e.mediaType
friendID.value = e.userID
callUserId.value = e.userID
console.log(e)
showLoading()
const res = await TUIUserService.getUserProfile({
userIDList: [e.userID]
})
hideLoading()
callerInfo.value = res.data[0]
if (e.type === 'call') {
CallLib.enableMicrophone(true)
CallLib.startSingleCall(callerInfo.value.userID, 0, 'answer')
}
if (e.callType == 'in') {
// 接听语音通话
callState.value = 'answer'
}
console.log('callState.value: ', callState.value)
console.log('===好友信息', res)
})
/** 按钮状态 */
const cutFn = show => {
if (show) {
// 接听电话 dialogue
if (mediaType.value === 'audio') {
CallLib.enableMicrophone(true)
}
CallLib.accept()
callState.value = 'dialogue'
// 开始计时
startTimer()
if (mediaType.value === 'video') {
uni.redirectTo({
url: "/pages/room/room"
})
}
} else {
// 停止计时
stopTimer()
// 取消接听,返回上一页
CallLib.hangup()
// navigateBack()
}
}
// 组件卸载时清理计时器
onUnload(() => {
stopTimer()
})
const mediaType = ref("audio")
onLoad(async e => {
callState.value = e.type
mediaType.value = e.mediaType
console.log(e)
showLoading()
const res = await TUIUserService.getUserProfile({
userIDList: [e.userID]
})
hideLoading()
callerInfo.value = res.data[0]
if (e.type === 'call') {
CallLib.enableMicrophone(true)
CallLib.startSingleCall(callerInfo.value.userID, 0, 'answer')
}
if (e.callType == "in") {
// 接听语音通话
callState.value = 'answer'
}
console.log('callState.value: ', callState.value);
console.log('===好友信息', res)
})
// 组件卸载时清理计时器
onUnload(() => {
stopTimer()
})
onUnmounted(() => {
stopTimer()
})
onUnmounted(() => {
stopTimer()
})
</script>
<template>
<!-- 来电接听界面 -->
<view class="incoming-call">
<!-- 背景模糊层 -->
<view class="blur-background" v-if="callBackground">
<image
:src="callBackground"
mode="aspectFill"
class="bg-image"
></image>
<view class="bg-overlay"></view>
</view>
<!-- 顶部栏 -->
<view class="top-bar">
<view class="top-left">
<!-- 通话时间显示 -->
<view v-if="callState === 'dialogue'" class="call-time-container">
<uni-icons type="sound" size="16" color="#fff"></uni-icons>
<text class="call-time">{{ formattedTime }}</text>
</view>
</view>
</view>
<!-- 主内容区 -->
<view class="caller-info">
<view class="caller-avatar-container">
<view class="caller-avatar" :class="{ 'avatar-ring': isRinging }">
<image
v-if="callerInfo?.avatar"
:src="callerInfo?.avatar"
class="avatar-image"
></image>
<uni-icons
v-else
type="contact-filled"
size="50"
color="#fff"
></uni-icons>
</view>
</view>
<text class="caller-name">
{{ callerInfo?.nick || callerInfo?.userID }}
</text>
<text class="call-type">
{{
callState === 'call'
? '呼叫中,等待对方接受邀请...'
: callState === 'answer'
? '等待接听...'
: '对话中...'
}}
</text>
<text class="call-status">
{{ mediaType === 'audio' ? '语音通话' : '视频通话' }}
</text>
</view>
<!-- 控制按钮 -->
<view class="incoming-controls">
<!-- 麦克风控制按钮仅在通话中显示 -->
<view
v-if="callState === 'dialogue'"
class="incoming-control"
@click="toggleMicrophone"
>
<view
class="call-btn mic-btn"
:class="{
'btn-active': activeBtn === 'mic',
'mic-muted': isMicMuted
}"
>
<uni-icons
v-if="!isMicMuted"
type="mic"
size="28"
color="#fff"
></uni-icons>
<uni-icons
v-else
type="micoff"
size="28"
color="#fff"
></uni-icons>
</view>
<text class="btn-text">{{ isMicMuted ? '开启' : '静音' }}</text>
</view>
<!-- 挂断/拒绝按钮 -->
<view class="incoming-control" @click="cutFn(false)">
<view
class="call-btn decline-btn"
:class="{ 'btn-active': activeBtn === 'decline' }"
>
<uni-icons type="closeempty" size="32" color="#fff"></uni-icons>
</view>
<text class="btn-text">
{{
callState === 'call' || callState == 'dialogue'
? '挂断'
: '拒绝'
}}
</text>
</view>
<!-- 接听按钮 -->
<view
v-if="callState === 'answer'"
class="incoming-control"
@click="cutFn(true)"
>
<view
class="call-btn accept-btn"
:class="{ 'btn-active': activeBtn === 'accept' }"
>
<uni-icons
type="checkmarkempty"
size="28"
color="#fff"
></uni-icons>
</view>
<text class="btn-text">接听</text>
</view>
<!-- 扬声器控制按钮仅在通话中显示 -->
<view
v-if="callState === 'dialogue'"
class="incoming-control"
@click="toggleSpeaker"
>
<view
class="call-btn speaker-btn"
:class="{
'btn-active': activeBtn === 'speaker',
'speaker-on': isSpeakerOn
}"
>
<uni-icons
v-if="!isSpeakerOn"
type="sound"
size="28"
color="#fff"
></uni-icons>
<uni-icons
v-else
type="sound-filled"
size="28"
color="#fff"
></uni-icons>
</view>
<text class="btn-text">扬声器</text>
</view>
</view>
</view>
</template>
<style lang="scss" scoped>
.incoming-call {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
display: flex;
flex-direction: column;
justify-content: space-between;
background-color: #000;
.incoming-call {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
display: flex;
flex-direction: column;
justify-content: space-between;
background-color: #000;
/* 顶部栏样式 */
.top-bar {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 120rpx;
display: flex;
align-items: center;
padding: 0 40rpx;
z-index: 2;
box-sizing: border-box;
padding-top: env(safe-area-inset-top);
/* 顶部栏样式 */
.top-bar {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 120rpx;
display: flex;
align-items: center;
padding: 0 40rpx;
z-index: 2;
box-sizing: border-box;
padding-top: env(safe-area-inset-top);
.top-left {
.call-time-container {
display: flex;
align-items: center;
background: rgba(255, 255, 255, 0.15);
padding: 8rpx 20rpx;
border-radius: 30rpx;
backdrop-filter: blur(10px);
.top-left {
.call-time-container {
display: flex;
align-items: center;
background: rgba(255, 255, 255, 0.15);
padding: 8rpx 20rpx;
border-radius: 30rpx;
backdrop-filter: blur(10px);
.call-time {
font-size: 28rpx;
color: #fff;
font-weight: 500;
margin-left: 10rpx;
}
}
}
}
.call-time {
font-size: 28rpx;
color: #fff;
font-weight: 500;
margin-left: 10rpx;
}
}
}
}
.blur-background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
.blur-background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
.bg-image {
width: 100%;
height: 100%;
filter: blur(20px);
opacity: 0.6;
}
.bg-image {
width: 100%;
height: 100%;
filter: blur(20px);
opacity: 0.6;
}
.bg-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
}
.bg-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
}
.caller-info {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding-top: 100rpx;
z-index: 1;
.caller-info {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding-top: 100rpx;
z-index: 1;
.caller-avatar-container {
position: relative;
margin-bottom: 40rpx;
.caller-avatar-container {
position: relative;
margin-bottom: 40rpx;
.caller-avatar {
width: 180rpx;
height: 180rpx;
border-radius: 50%;
background: linear-gradient(135deg, #1aad19, #129611);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
.caller-avatar {
width: 180rpx;
height: 180rpx;
border-radius: 50%;
background: linear-gradient(135deg, #1aad19, #129611);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
.avatar-image {
width: 100%;
height: 100%;
}
.avatar-image {
width: 100%;
height: 100%;
}
&.avatar-ring {
animation: ringPulse 1.5s infinite;
}
}
}
&.avatar-ring {
animation: ringPulse 1.5s infinite;
}
}
}
.caller-name {
font-size: 48rpx;
color: #fff;
font-weight: 500;
margin-bottom: 20rpx;
}
.caller-name {
font-size: 48rpx;
color: #fff;
font-weight: 500;
margin-bottom: 20rpx;
}
.call-type {
font-size: 32rpx;
color: rgba(255, 255, 255, 0.9);
margin-bottom: 10rpx;
}
.call-type {
font-size: 32rpx;
color: rgba(255, 255, 255, 0.9);
margin-bottom: 10rpx;
}
.call-status {
font-size: 28rpx;
color: rgba(255, 255, 255, 0.7);
}
}
.call-status {
font-size: 28rpx;
color: rgba(255, 255, 255, 0.7);
}
}
.incoming-controls {
display: flex;
justify-content: space-around;
padding: 80rpx 40rpx 120rpx;
z-index: 1;
.incoming-controls {
display: flex;
justify-content: space-around;
padding: 80rpx 40rpx 120rpx;
z-index: 1;
.incoming-control {
display: flex;
flex-direction: column;
align-items: center;
min-width: 120rpx;
.incoming-control {
display: flex;
flex-direction: column;
align-items: center;
min-width: 120rpx;
.call-btn {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20rpx;
transition: all 0.2s;
.call-btn {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20rpx;
transition: all 0.2s;
&.decline-btn {
background-color: #f43f3b;
&.decline-btn {
background-color: #f43f3b;
&.btn-active {
transform: scale(0.9);
background-color: #d93632;
}
}
&.btn-active {
transform: scale(0.9);
background-color: #d93632;
}
}
&.accept-btn {
background-color: #07c160;
&.accept-btn {
background-color: #07c160;
&.btn-active {
transform: scale(0.9);
background-color: #06ad56;
}
}
&.btn-active {
transform: scale(0.9);
background-color: #06ad56;
}
}
&.mic-btn {
background-color: rgba(255, 255, 255, 0.2);
&.mic-btn {
background-color: rgba(255, 255, 255, 0.2);
&.mic-muted {
background-color: rgba(255, 255, 255, 0.1);
}
&.mic-muted {
background-color: rgba(255, 255, 255, 0.1);
}
&.btn-active {
transform: scale(0.9);
background-color: rgba(255, 255, 255, 0.3);
}
}
&.btn-active {
transform: scale(0.9);
background-color: rgba(255, 255, 255, 0.3);
}
}
&.speaker-btn {
background-color: rgba(255, 255, 255, 0.2);
&.speaker-btn {
background-color: rgba(255, 255, 255, 0.2);
&.speaker-on {
background-color: rgba(255, 255, 255, 0.3);
}
&.speaker-on {
background-color: rgba(255, 255, 255, 0.3);
}
&.btn-active {
transform: scale(0.9);
background-color: rgba(255, 255, 255, 0.3);
}
}
}
&.btn-active {
transform: scale(0.9);
background-color: rgba(255, 255, 255, 0.3);
}
}
}
.btn-text {
font-size: 24rpx;
color: #fff;
text-align: center;
}
}
}
}
.btn-text {
font-size: 24rpx;
color: #fff;
text-align: center;
}
}
}
}
@keyframes ringPulse {
0% {
box-shadow: 0 0 0 0 rgba(26, 173, 25, 0.4);
}
@keyframes ringPulse {
0% {
box-shadow: 0 0 0 0 rgba(26, 173, 25, 0.4);
}
70% {
box-shadow: 0 0 0 30rpx rgba(26, 173, 25, 0);
}
70% {
box-shadow: 0 0 0 30rpx rgba(26, 173, 25, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(26, 173, 25, 0);
}
}
100% {
box-shadow: 0 0 0 0 rgba(26, 173, 25, 0);
}
}
/* 响应式调整 */
@media (max-height: 600px) {
.incoming-controls {
padding: 40rpx 30rpx 80rpx !important;
}
}
</style>
/* 响应式调整 */
@media (max-height: 600px) {
.incoming-controls {
padding: 40rpx 30rpx 80rpx !important;
}
}
</style>

View File

@@ -1,419 +1,461 @@
import { defineStore } from 'pinia'
import {
defineStore
} from 'pinia'
import {
getToken,
getUserInfoData,
setUserInfoData,
removeUserInfoData,
getSig,
setSig,
removeSig,
getFontSize,
setFontSize,
removeFontSize
getToken,
getUserInfoData,
setUserInfoData,
removeUserInfoData,
getSig,
setSig,
removeSig,
getFontSize,
setFontSize,
removeFontSize
} from '@/utils/storage'
// #ifdef APP-PLUS
import {
useLoginState
} from '@/uni_modules/tuikit-atomic-x/state/LoginState'
import { useLoginState } from '@/uni_modules/tuikit-atomic-x/state/LoginState'
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import RCIMIWEngine from '@/uni_modules/RongCloud-IMWrapper-V2/js_sdk/RCIMEngine'
import {
reasonDeal,
errorDeal,
imCode
} from '@/utils/code.js'
import { reasonDeal, errorDeal, imCode } from '@/utils/code.js'
// #endif
// #ifdef H5
import {
useLoginState
} from 'tuikit-atomicx-vue3'
import { useLoginState } from 'tuikit-atomicx-vue3'
// #endif
import {
useTokenStore
} from './token'
import {
getUserData,
userLogout,
updateUserData
} from '@/api'
import {
ref
} from 'vue'
import {
useUI
} from '@/utils/use-ui'
import {
reLaunch
} from '@/utils/router'
import {
getTencentUserSig
} from '@/api'
import {
TUILogin
} from '@tencentcloud/tui-core-lite'
import {
TUIChatEngine
} from '@tencentcloud/chat-uikit-engine-lite'
import {
getUserIntegral
} from '@/api/my-index'
import {
removeFriendList,
removeGroupList
} from '../utils/storage'
import {
getRongYunLoginInfo
} from '../api'
import permision from "@/js_sdk/wa-permission/permission.js"
import { useTokenStore } from './token'
import { getUserData, userLogout, updateUserData } from '@/api'
import { ref } from 'vue'
import { useUI } from '@/utils/use-ui'
import { reLaunch } from '@/utils/router'
import { getTencentUserSig } from '@/api'
import { TUILogin } from '@tencentcloud/tui-core-lite'
import { TUIChatEngine } from '@tencentcloud/chat-uikit-engine-lite'
import { getUserIntegral } from '@/api/my-index'
import { removeFriendList, removeGroupList } from '../utils/storage'
import { getRongYunLoginInfo } from '../api'
import permision from '@/js_sdk/wa-permission/permission.js'
import { navigateTo } from '@/utils/router'
import { sendCallMsg } from '../utils/call-user'
export const useUserStore = defineStore('user', () => {
const {
clearToken
} = useTokenStore()
const {
showDialog,
showToast
} = useUI()
const { clearToken } = useTokenStore()
const { showDialog, showToast } = useUI()
const userInfo = ref(
getUserInfoData() ? JSON?.parse(getUserInfoData()) : {}
)
/** 用户字体大小 */
const fontSizeData = ref(getFontSize())
const userInfo = ref(
getUserInfoData() ? JSON?.parse(getUserInfoData()) : {}
)
/** 用户字体大小 */
const fontSizeData = ref(getFontSize())
/** 腾讯 IM 存储数据 */
const tencentUserSig = ref(getSig() ? JSON?.parse(getSig()) : {})
/** 腾讯 IM 存储数据 */
const tencentUserSig = ref(getSig() ? JSON?.parse(getSig()) : {})
/** 用户积分数 */
const integralData = ref(0)
/** 融云 IM 引擎 */
const imEngine = ref(null)
/** 用户积分数 */
const integralData = ref(0)
/** 融云 IM 引擎 */
const imEngine = ref(null)
/** 发起通话用户id */
const callUserId = ref('')
/** 通话时长(秒) */
const callDuration = ref(0)
/** 通话模式 0语音通话 1视频通话 */
const callMode = ref('0')
/** 通话计时器 */
const timer = ref(null)
/**
* 获取用户信息(可从缓存或接口)
*/
const fetchUserInfo = async () => {
// 尝试从本地缓存读取
const cachedToken = getToken()
const cachedUserInfo = getUserInfoData()
const cachedSig = getSig()
/** 开始通话计时 */
const startTimer = () => {
stopTimer() // 先停止之前的计时器
timer.value = setInterval(() => {
callDuration.value++
}, 1000)
}
if (cachedToken && cachedUserInfo) {
userInfo.value = JSON.parse(cachedUserInfo)
tencentUserSig.value = JSON.parse(cachedSig)
loginTencentIM()
return
}
await getIntegral()
const res = await getUserData()
await setUserInfo(res.data)
loginTencentIM()
return
}
/** 停止通话计时 */
const stopTimer = () => {
if (timer.value) {
clearInterval(timer.value)
timer.value = null
}
}
/**
* 设置用户信息
*/
const setUserInfo = async data => {
const res = await getTencentUserSig()
const ryData = await getRongYunLoginInfo()
const IM_DATA = {
...res.data,
...ryData.data
}
tencentUserSig.value = IM_DATA
userInfo.value = data
setUserInfoData(data)
setSig(IM_DATA)
}
/** 重置时间 */
const resetTime = () => {
callDuration.value = 0
}
/** 通话模式更新 */
const updateCallMode = mode => {
callMode.value = mode
}
/** 获取用户积分 */
const getIntegral = async () => {
const res = await getUserIntegral()
integralData.value = res.data.availablePoints
}
/**
* 获取用户信息(可从缓存或接口)
*/
const fetchUserInfo = async () => {
// 尝试从本地缓存读取
const cachedToken = getToken()
const cachedUserInfo = getUserInfoData()
const cachedSig = getSig()
/**
* 登录腾讯 IM
*/
const loginTencentIM = async () => {
await refreshUserInfo()
await TUILogin.login({
SDKAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig,
framework: `vue3`
})
if (cachedToken && cachedUserInfo) {
userInfo.value = JSON.parse(cachedUserInfo)
tencentUserSig.value = JSON.parse(cachedSig)
loginTencentIM()
return
}
await getIntegral()
const res = await getUserData()
await setUserInfo(res.data)
loginTencentIM()
return
}
await TUIChatEngine.login({
SDKAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig,
useUploadPlugin: true // 使用文件上传插件
})
// #ifdef H5
await useLoginState().login({
SDKAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig
})
// #endif
/**
* 设置用户信息
*/
const setUserInfo = async data => {
const res = await getTencentUserSig()
const ryData = await getRongYunLoginInfo()
const IM_DATA = {
...res.data,
...ryData.data
}
tencentUserSig.value = IM_DATA
userInfo.value = data
setUserInfoData(data)
setSig(IM_DATA)
}
// #ifdef APP-PLUS
await useLoginState().login({
sdkAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig
})
console.log(tencentUserSig.value.appKey, '====')
await connectIM()
// #endif
}
/** 获取用户积分 */
const getIntegral = async () => {
const res = await getUserIntegral()
integralData.value = res.data.availablePoints
}
//连接融云IM
const connectIM = async () => {
let options = {}
imEngine.value = await RCIMIWEngine.create(tencentUserSig.value.appKey, options)
imEngine.value.setOnConnectedListener((res) => {
if (res.code != 0) {
uni.hideLoading();
// uni.showToast({
// title: 'OnCon:' + res.code,
// icon: 'error'
// })
console.log("连接已存在");
// return
}
//连接成功
CallLib.init({});
console.log('call.init')
uni.hideLoading();
uni.showToast({
title: res.userId
});
if (uni.getSystemInfoSync().platform === 'android') {
permision.requestAndroidPermission('android.permission.CAMERA');
permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
}
onAllListeners()
});
let code = await imEngine.value.connect(tencentUserSig.value.ryToken, 10)
if (code != 0) {
uni.hideLoading();
uni.showToast({
title: 'connect:' + code,
icon: 'error'
})
}
}
function onAllListeners () {
CallLib.onCallReceived( (res)=> {
console.log(res)
console.log("Engine:OnCallReceived=>"+"监听通话呼入, 目标id=>", res.data.targetId);
if (res.data.targetId) {
// let url = res.data.mediaType == 0 ? "" : "/pages/room/room"
uni.setStorageSync('room-parameters', {
callType: 'in',
mediaType: res.data.mediaType === 0 ? 'audio' : 'video'
});
uni.showToast({
title:"有通话呼入该跳转了"+res.data.targetId,
duration:3000
})
navigateTo("/pages/room/incom", {
type: res.data.extra,
callType: 'in',
mediaType: res.data.mediaType == 0 ? "audio" : "video",
userID: res.data.mine.userId // 对方的用户id
})
}
});
CallLib.onCallDisconnected((res)=>{
console.log(res)
console.log("Engine:OnCallDisconnected=>"+"通话挂断/拒绝, 挂断原因=>", res.data.reason);
// 重新渲染视频视图
// uni.$emit('OnCallDisconnected');
uni.showToast({
title:reasonDeal(res.data.reason),
error:"error",
icon:'none',
duration:2000
})
goback()
});
CallLib.onCallConnected((res)=>{
console.log(res)
console.log("Engine:OnCallConnected=>"+"已建立通话通话接通时,通过回调 onCallConnected 通知当前 call 的详细信息", res);
});
CallLib.onRemoteUserInvited((res)=>{
console.log("Engine:OnRemoteUserInvited=>"+"通话中的某一个参与者,邀请好友加入通话 ,远端Id为=>", res.data.userId);
uni.$emit('OnCallConnected');
})
CallLib.onRemoteUserJoined((res)=>{
console.log("Engine:OnRemoteUserJoined=>"+"主叫端拨出电话被叫端收到请求后加入通话对端Id为=>", res.data.userId);
uni.$emit('OnCallConnected');
})
CallLib.onRemoteUserLeft((res)=>{
console.log("Engine:OnRemoteUserLeft=>"+"远端用户挂断(群聊触发)远端Id为=>", res.data.reason);
uni.$emit('OnCallConnected');
uni.showToast({
title:reasonDeal(res.data.reason),
error:"error",
icon:'none',
duration:2000
})
})
CallLib.onCallOutgoing((res)=>{
console.log('电话已拨出 主叫端拨出电话后,通过回调 onCallOutgoing 通知当前 call 的详细信息')
})
CallLib.onRemoteUserRinging((res)=>{
console.log('被叫端正在振铃,主叫端拨出电话,被叫端收到请求,发出振铃响应时,回调 onRemoteUserRingin,对端Id为=>', res.data.userId)
})
CallLib.onError((res)=>{
console.log('通话过程中,发生异常')
uni.showToast({
title:errorDeal(res.data.reason),
error:"error",
icon:'none',
duration:2000
});
goback()
})
CallLib.onRemoteUserMediaTypeChanged((res)=>{
console.log('当通话中的某一个参与者切换通话类型,例如由 audio 切换至 video回调 onMediaTypeChanged,切换媒体类型的Id为=>',res.data.user.userId);
})
}
function goback () {
const pages = getCurrentPages()
console.log('pages: ',pages);
if (pages.length > 1) {
console.log("走返回");
uni.showToast({
title:"走返回",
duration:3000
})
uni.navigateBack({
delta: 1
})
const currentPage = pages[pages.length - 1]
const prevPage = pages[pages.length - 2]
// 判断上一页是否是 tabBar 页面
// const isPrevPageTabBar = isTabBarPage(currentPage.route)
// if(!isPrevPageTabBar){
// }
}
}
// 判断页面是否是 tabBar 页面
function isTabBarPage(route) {
// 这里根据你的 pages.json 配置来判断
const tabBarPages = [
'TUIKit/components/TUIConversation/index',
'TUIKit/components/TUIContact/index',
'pages/discover/discover',
'pages/my-index/my-index'
]
// 判断路由是否在 tabBar 页面列表中
return tabBarPages.includes(route)
}
/**
* 登录腾讯 IM
*/
const loginTencentIM = async () => {
await refreshUserInfo()
await TUILogin.login({
SDKAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig,
framework: `vue3`
})
/**
* 清除用户信息(退出登录)
*/
const clearUserInfo = async () => {
const show = await showDialog('提示', '确定要退出登录吗?')
if (show) {
await logout()
}
}
await TUIChatEngine.login({
SDKAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig,
useUploadPlugin: true // 使用文件上传插件
})
// #ifdef H5
await useLoginState().login({
SDKAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig
})
// #endif
/**
* 退出登录(不带提示)
*/
const logout = async () => {
if (!userInfo.value) return
try {
userInfo.value = null
// #ifdef APP-PLUS
await useLoginState().login({
sdkAppID: tencentUserSig.value.sdkappID,
userID: tencentUserSig.value.userId,
userSig: tencentUserSig.value.userSig
})
console.log(tencentUserSig.value.appKey, '====')
await connectIM()
// #endif
}
await userLogout()
await TUILogin.logout()
await TUIChatEngine.logout()
// #ifdef APP-PLUS
removeFriendList()
removeGroupList()
await useLoginState().logout()
// #endif
// #ifdef H5
await useLoginState().logout()
// #endif
clearAllUserInfo()
await showToast('退出登录成功', 'success')
reLaunch('/pages/login/login')
} catch (error) {
clearAllUserInfo()
await showToast('退出登录成功', 'success')
reLaunch('/pages/login/login')
}
}
//连接融云IM
const connectIM = async () => {
let options = {}
imEngine.value = await RCIMIWEngine.create(
tencentUserSig.value.appKey,
options
)
imEngine.value.setOnConnectedListener(res => {
if (res.code != 0) {
uni.hideLoading()
// uni.showToast({
// title: 'OnCon:' + res.code,
// icon: 'error'
// })
console.log('连接已存在')
// return
}
//连接成功
CallLib.init({})
console.log('call.init')
uni.hideLoading()
// uni.showToast({
// title: res.userId
// })
console.log('登录成功')
if (uni.getSystemInfoSync().platform === 'android') {
permision.requestAndroidPermission('android.permission.CAMERA')
permision.requestAndroidPermission(
'android.permission.RECORD_AUDIO'
)
}
onAllListeners()
})
let code = await imEngine.value.connect(
tencentUserSig.value.ryToken,
10
)
if (code != 0) {
uni.hideLoading()
uni.showToast({
title: 'connect:' + code,
icon: 'error'
})
}
}
/** 清空所有用户缓存 */
const clearAllUserInfo = async () => {
userInfo.value = null
tencentUserSig.value = null
fontSizeData.value = 26
clearToken()
removeUserInfoData()
removeSig()
removeFontSize()
}
function onAllListeners() {
CallLib.onCallReceived(res => {
console.log(res)
console.log(
'Engine:OnCallReceived=>' + '监听通话呼入, 目标id=>',
res.data.targetId
)
if (res.data.targetId) {
// let url = res.data.mediaType == 0 ? "" : "/pages/room/room"
uni.setStorageSync('room-parameters', {
callType: 'in',
mediaType: res.data.mediaType === 0 ? 'audio' : 'video'
})
uni.showToast({
title: '有通话呼入该跳转了' + res.data.targetId,
duration: 3000
})
navigateTo('/pages/room/incom', {
type: res.data.extra,
callType: 'in',
mediaType: res.data.mediaType == 0 ? 'audio' : 'video',
userID: res.data.mine.userId // 对方的用户id
})
}
})
CallLib.onCallDisconnected(res => {
console.log(res)
console.log(
'Engine:OnCallDisconnected=>' + '通话挂断/拒绝, 挂断原因=>',
res.data.reason
)
console.log('=====通话用户id', callUserId.value)
sendCallMsg(res.data.reason)
// 重新渲染视频视图
// uni.$emit('OnCallDisconnected');
uni.showToast({
title: reasonDeal(res.data.reason),
error: 'error',
icon: 'none',
duration: 2000
})
goback()
})
CallLib.onCallConnected(res => {
console.log(res)
console.log(
'Engine:OnCallConnected=>' +
'已建立通话通话接通时,通过回调 onCallConnected 通知当前 call 的详细信息',
res
)
})
CallLib.onRemoteUserInvited(res => {
console.log(
'Engine:OnRemoteUserInvited=>' +
'通话中的某一个参与者,邀请好友加入通话 ,远端Id为=>',
res.data.userId
)
uni.$emit('OnCallConnected')
})
CallLib.onRemoteUserJoined(res => {
console.log(
'Engine:OnRemoteUserJoined=>' +
'主叫端拨出电话被叫端收到请求后加入通话对端Id为=>',
res.data.userId
)
uni.$emit('OnCallConnected')
})
CallLib.onRemoteUserLeft(res => {
console.log(
'Engine:OnRemoteUserLeft=>' +
'远端用户挂断(群聊触发)远端Id为=>',
res.data.reason
)
uni.$emit('OnCallConnected')
uni.showToast({
title: reasonDeal(res.data.reason),
error: 'error',
icon: 'none',
duration: 2000
})
})
CallLib.onCallOutgoing(res => {
console.log(
'电话已拨出 主叫端拨出电话后,通过回调 onCallOutgoing 通知当前 call 的详细信息'
)
})
CallLib.onRemoteUserRinging(res => {
console.log(
'被叫端正在振铃,主叫端拨出电话,被叫端收到请求,发出振铃响应时,回调 onRemoteUserRingin,对端Id为=>',
res.data.userId
)
})
CallLib.onError(res => {
console.log('通话过程中,发生异常')
uni.showToast({
title: errorDeal(res.data.reason),
error: 'error',
icon: 'none',
duration: 2000
})
goback()
})
CallLib.onRemoteUserMediaTypeChanged(res => {
console.log(
'当通话中的某一个参与者切换通话类型,例如由 audio 切换至 video回调 onMediaTypeChanged,切换媒体类型的Id为=>',
res.data.user.userId
)
})
}
/** 刷新用户信息(如用户信息被修改) */
const refreshUserInfo = async () => {
const res = await getUserData()
await getIntegral()
await setUserInfoData(res.data)
userInfo.value = res.data
}
function goback() {
const pages = getCurrentPages()
console.log('pages: ', pages)
if (pages.length > 1) {
console.log('走返回')
uni.showToast({
title: '走返回',
duration: 3000
})
uni.navigateBack({
delta: 1
})
const currentPage = pages[pages.length - 1]
const prevPage = pages[pages.length - 2]
/**
* 更新部分用户信息(例如昵称、头像)
*/
const updateUserInfo = async partialData => {
if (!userInfo.value) return
await updateUserData(partialData)
await refreshUserInfo()
}
// 判断上一页是否是 tabBar 页面
// const isPrevPageTabBar = isTabBarPage(currentPage.route)
// if(!isPrevPageTabBar){
/** 更新字体大小 */
const updateFontSize = async fontSize => {
fontSizeData.value = fontSize
setFontSize(fontSize)
}
// }
}
}
return {
imEngine,
userInfo,
integralData,
tencentUserSig,
fontSizeData,
getIntegral,
clearAllUserInfo,
updateFontSize,
logout,
refreshUserInfo,
fetchUserInfo,
loginTencentIM,
setUserInfo,
clearUserInfo,
updateUserInfo
}
})
// 判断页面是否是 tabBar 页面
function isTabBarPage(route) {
// 这里根据你的 pages.json 配置来判断
const tabBarPages = [
'TUIKit/components/TUIConversation/index',
'TUIKit/components/TUIContact/index',
'pages/discover/discover',
'pages/my-index/my-index'
]
// 判断路由是否在 tabBar 页面列表中
return tabBarPages.includes(route)
}
/**
* 清除用户信息(退出登录)
*/
const clearUserInfo = async () => {
const show = await showDialog('提示', '确定要退出登录吗?')
if (show) {
await logout()
}
}
/**
* 退出登录(不带提示)
*/
const logout = async () => {
if (!userInfo.value) return
try {
userInfo.value = null
await userLogout()
await TUILogin.logout()
await TUIChatEngine.logout()
// #ifdef APP-PLUS
removeFriendList()
removeGroupList()
await useLoginState().logout()
// #endif
// #ifdef H5
await useLoginState().logout()
// #endif
clearAllUserInfo()
await showToast('退出登录成功', 'success')
reLaunch('/pages/login/login')
} catch (error) {
clearAllUserInfo()
await showToast('退出登录成功', 'success')
reLaunch('/pages/login/login')
}
}
/** 清空所有用户缓存 */
const clearAllUserInfo = async () => {
userInfo.value = null
tencentUserSig.value = null
fontSizeData.value = 26
clearToken()
removeUserInfoData()
removeSig()
removeFontSize()
}
/** 刷新用户信息(如用户信息被修改) */
const refreshUserInfo = async () => {
const res = await getUserData()
await getIntegral()
await setUserInfoData(res.data)
userInfo.value = res.data
}
/**
* 更新部分用户信息(例如昵称、头像)
*/
const updateUserInfo = async partialData => {
if (!userInfo.value) return
await updateUserData(partialData)
await refreshUserInfo()
}
/** 更新字体大小 */
const updateFontSize = async fontSize => {
fontSizeData.value = fontSize
setFontSize(fontSize)
}
return {
callUserId,
callDuration,
imEngine,
userInfo,
integralData,
tencentUserSig,
fontSizeData,
callMode,
startTimer,
stopTimer,
updateCallMode,
resetTime,
getIntegral,
clearAllUserInfo,
updateFontSize,
logout,
refreshUserInfo,
fetchUserInfo,
loginTencentIM,
setUserInfo,
clearUserInfo,
updateUserInfo
}
})

59
utils/call-user.js Normal file
View File

@@ -0,0 +1,59 @@
import TUIChatEngine, {
TUIChatService
} from '@tencentcloud/chat-uikit-engine-lite'
import { CHAT_MSG_CUSTOM_TYPE } from '../TUIKit/constant'
import { useAuthUser } from '../composables/useAuthUser'
import { useUserStore } from '../stores/user'
/** 格式化时间显示 */
const formatTime = date => {
const minutes = Math.floor(date / 60)
const seconds = date % 60
return `${minutes.toString().padStart(2, '0')}:${seconds
.toString()
.padStart(2, '0')}`
}
/** 通话消息发送 */
export const sendCallMsg = async state => {
const { resetTime, stopTimer } = useUserStore()
const { callUserId, callMode, callDuration, tencentUserSig } =
useAuthUser()
const to = callUserId.value
const userID = tencentUserSig.value.userId
if (to !== userID) {
let title = ''
if ([0, 11].includes(state)) {
title = { 0: '已挂断', 11: '对方已拒绝' }[state]
} else {
title = `通话时长 ${formatTime(callDuration.value)}`
}
const payload = {
data: JSON.stringify({
businessID:
callMode.value == 0
? CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
: CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL,
title,
userID: to
}),
description: title,
extension: title
}
const options = {
to,
payload,
conversationType: TUIChatEngine.TYPES.CONV_C2C,
needReadReceipt: false
}
resetTime()
await TUIChatService.sendCustomMessage(options)
} else {
resetTime()
}
if (callMode.value == 1) {
stopTimer()
}
}