国产亚洲精品福利在线无卡一,国产精久久一区二区三区,亚洲精品无码国模,精品久久久久久无码专区不卡

當前位置: 首頁 > news >正文

平臺門戶網(wǎng)站建設站外推廣渠道有哪些

平臺門戶網(wǎng)站建設,站外推廣渠道有哪些,cnzz統(tǒng)計代碼如何添加到網(wǎng)站上去,wordpress主題插件比這之前優(yōu)化了以下功能 上線通知 群聊里適時顯示在線人數(shù) 約請好友 通過好友通過socket 相應端自動變化 PC端可以拉取攝象頭拍照 PC端可以錄音發(fā)送 拉起攝象頭發(fā)送錄象 <template><view class""><scroll-view scroll-y"true" class&…
比這之前優(yōu)化了以下功能
上線通知
群聊里適時顯示在線人數(shù)
約請好友 通過好友通過socket 相應端自動變化
PC端可以拉取攝象頭拍照
PC端可以錄音發(fā)送
拉起攝象頭發(fā)送錄象

在這里插入圖片描述

<template><view class=""><scroll-view scroll-y="true" class="scroll-box":style="{ height: `${windowObj.windowHeight - windowObj.statusBarHeight - 94}px` }":scroll-top="scrollHeight" @scrolltoupper="loadMores"><view class="group-box">在線{{userList.length}}人:<text class="group-member" v-for="(item, index) in userList" :key="index">{{item}} </text></view><view class="scroll-view"><view class="news-box" v-for="(item, index) in list" :key="index"><view class="message-type" v-if="['left', 'join', 'kick'].includes(item.type)">{{ item.content }} {{(formatDate(Date()))}}</view><image class="avatar" :class="[item.isMe ? 'is-me' : 'avatar-right']" :src="item.avatar"mode="aspectFill" v-if="!['kick', 'join', 'left'].includes(item.type)" @tap="kickopen(item)"></image><view class="message-box" :class="{ 'is-me': item.isMe }"v-if="!['kick', 'join', 'left'].includes(item.type)"><text class="message" v-if="item.type === 'text'"><image src="../../static/withdraw.png"style="width: 40rpx; height: 40rpx;position:relative;right:16rpx;bottom:1rpx;"mode="aspectFill" v-if="item.isMe && canwithdraw(item) && item.withdraw === 0"@tap="withdraw(item)"></image><text :selectable="true" @tap="copyBtnClick(item.content)" > {{formatMessage(item.content || '')}}</text></text><text class="message_img" v-if="['image', 'video', 'audio'].includes(item.type)"><template v-if="item.type === 'image'"><image class="message-image" :src="item.content" mode="aspectFill"@click="previewImage(item.content)" /></template><template v-if="item.type === 'video'"><video v-if="item.content" :src="item.content" controls></video></template><template v-if="item.type === 'audio'"><audio v-if="item.content" :src="item.content" controls ></audio></template><image src="../../static/withdraw.png" style="width: 50rpx; height: 50rpx" mode="aspectFill"v-if="item.isMe && canwithdraw(item) && item.withdraw === 0" @click="withdraw(item)"></image></text></view></view></view></scroll-view><view class="base-btn" :class="{ 'base-btn-popup-open': isPopupOpen || isPopupAudioOpen }"><view class="base-con unify-flex"><view @tap="more"><image src="../../static/chat/more.png" style="width: 50rpx; height: 50rpx"></image></view><input class="input-text" type="text" :value="inputValue" placeholder="說些什么吧" @input="getInput"@confirm="tapTo(2)" /><view @click="tapTo(2)"><image src="../../static/chat/chat.png" style="width: 50rpx; height: 50rpx"></image></view></view></view><uni-popup ref="popup" type="bottom" :style="{ height: '200rpx' }" @change="onPopupChange"><view class="popup-content":style="{ width: '100%', backgroundColor: '#fff', height: '200rpx', overflowY: 'scroll' }"><view class="popup-items"><view class="popup-item" v-if="type === 'group'" @tap="adduserTogroup"><image src="../../static/chat/add.png" style="width: 50rpx; height: 50rpx"></image><text>添加</text></view><view class="popup-item" @click="chooseFile"><image src="../../static/chat/pic.png" style="width: 50rpx; height: 50rpx"></image><text>圖片</text></view><view class="popup-item" @tap="audio"><image src="../../static/chat/audio.png" style="width: 50rpx; height: 50rpx"></image><text>音頻</text></view><view class="popup-item" @tap="openCamera"><image src="../../static/chat/video.png" style="width: 50rpx; height: 50rpx"></image><text>視頻</text></view><view class="popup-item" @tap="groupdetail"><image src="../../static/chat/detail.png" style="width: 50rpx; height: 50rpx"></image><text>詳情</text></view><view class="popup-item" v-if="type === 'group'" @tap="quitgroup"><image src="../../static/chat/exit-group.png" style="width: 50rpx; height: 50rpx"></image><text>退群</text></view></view></view></uni-popup><uni-popup ref="popupAudio" type="bottom" :style="{ height: '200rpx' }" @change="onPopupAudioChange"><view class="popup-content":style="{ width: '100%', backgroundColor: '#fff', height: '200rpx', overflowY: 'scroll' }"><view class="popup-item" @click="startRecording"><image src="../../static/chat/beginaudio.png" style="width: 50rpx; height: 50rpx"></image><text>錄音</text></view><view class="popup-item" @click="stopRecording"><image src="../../static/chat/send.png" style="width: 50rpx; height: 50rpx"></image><text>發(fā)送錄音</text></view><!-- 		<view class="popup-item" @tap="playRecording"><image src="../../static/chat/play.png" style="width: 50rpx; height: 50rpx"></image><text>播放</text></view> --><!-- 	<view class="popup-item" @tap="upsong"><image src="../../static/chat/send.png" style="width: 50rpx; height: 50rpx"></image><text>發(fā)送</text></view> --><view class="popup-item" @tap="exitchat"><image src="../../static/chat/exit.png" style="width: 50rpx; height: 50rpx"></image><text>退出</text></view></view></uni-popup><uni-popup ref="popupkick" type="bottom" :style="{ height: '200rpx' }" @change="onPopupAudioChange"><view class="popup-content":style="{ width: '100%', backgroundColor: '#fff', height: '200rpx', overflowY: 'scroll' }"><view class="popup-item" @click="kick('kick')"><image src="../../static/chat/kickp.png" style="width: 50rpx; height: 50rpx"></image><text>踢人</text></view><view class="popup-item" @click="kick('black')"><image src="../../static/chat/black.png" style="width: 50rpx; height: 50rpx"></image><text>拉黑</text></view><view class="popup-item" @tap="detail"><image src="../../static/chat/detail.png" style="width: 50rpx; height: 50rpx"></image><text>詳情</text></view></view></uni-popup></view>
</template>
<script>import io from 'socket.io-client';import config from '@/config/config.js';import {mapState,mapActions} from 'vuex';import {v4 as uuidv4} from 'uuid';import {getCurrentDateTime} from '@/common/dateFormatter.js'import { handleClipboard } from '@/common/clipboardone.js';export default {data() {return {name: '',inputValue: '',list: [],image: '',scrollHeight: 0,userList: '',type: '',socket: null,messages: [],groupName: '',tid: '',toid: 0,receiver_type: '',isPopupOpen: false,isPopupAudioOpen: false,selectedFilePath: '',group_owner_id: 0, //群主idfid: '',to_id: 0,recordingPath: '', // 用于存儲錄音文件的路徑isRecording: false,mediaRecorder: null,audioChunks: []};},computed: {...mapState(['user']),windowObj() {let obj;uni.getSystemInfo({success: (res) => {obj = res;}});return obj;}},watch: {isPopupOpen(newValue) {if (!newValue) {this.$refs.popup.close();}},isPopupAudioOpen(newValue) {if (!newValue) {this.$refs.popupAudio.close();}}},async onLoad(q) {let _ = this;try {if (q && q.id != undefined) {this.groupName = q.id;this.tid = q.tid;this.to_id = q.to_idthis.receiver_type = q.type;this.type = this.receiver_typeuni.setNavigationBarTitle({title: q.type == 'group' ? '[群聊] '+q.to_name: '[私聊] '+q.to_name});if (q.type == 'group') {//將q.id的前面g_去掉let newid = q.id.replace('g_', '')//獲到了當前群的群主idlet re = await _.getGroupOwner(newid)this.group_owner_id = re.data.data.owner_id}let re = await _.checkFriend(q.id);if (re == true) {_.joinGroup(this.groupName);} else {uni.navigateTo({url: '/pages/index/friends'});}} else {uni.navigateTo({url: '/pages/index/friends'});}} catch (e) {uni.navigateTo({url: '/pages/index/friends'});}},onUnload() {this.socket.close();},onShow() {this.fetchUser();},mounted() {this.initChatLog();this.socket = io(config.apiBaseUrl);this.socket.on('connect', () => {console.log('Socket connected:', this.socket.id);});this.socket.on('disconnect', () => {console.log('Socket disconnected');});let heartbeatInterval;let reconnectAttempts = 0;const maxReconnectAttempts = 10;const startHeartbeat = () => {heartbeatInterval = setInterval(() => {if (this.socket.connected) {this.socket.emit('heartbeat');console.log('heartbeat')} else {reconnectSocket();}}, 120000); // 1分鐘};const reconnectSocket = () => {if (reconnectAttempts < maxReconnectAttempts) {this.socket.connect();reconnectAttempts++;} else {clearInterval(heartbeatInterval);uni.showModal({title: '連接失敗',content: '無法連接到服務器,是否手動重新連接?',confirmText: '重新連接',cancelText: '取消',success: (res) => {if (res.confirm) {reconnectAttempts = 0;this.socket.connect();startHeartbeat();}}});}};startHeartbeat();this.socket.on('reconnect', () => {console.log('Socket重新連接成功');reconnectAttempts = 0;});this.socket.on('message', (msg) => {if (msg.type == 'broadcast') {return;}if (msg.type == 'widthdraw') {//查出 msg.sn 將此記錄信息改為撤回//console.log(msg);this.list.forEach((item, index) => {if (item.sn == msg.content) {this.list[index].content = '[消息已撤回]';this.list[index].type = 'text';this.list[index].withdraw = 1;this.widthdrawRow(item.sn)}});return;}let msgs = {sn: msg.sn,name: msg.user_name,avatar: msg.avatar,isMe: msg.fid == this.user.id ? true : false,content: msg.content,type: msg.type,sn: msg.sn,createat: Math.floor(Date.now() / 1000),time: Date.now(),withdraw: 0,toid: msg.fid};this.list.push(msgs);this.setScrollTop();});// 監(jiān)聽 'userList' 事件this.socket.on('userList', (users) => {this.userList = users; // 更新 userList 變量console.log('- 當前群用戶 -')console.log(this.userList)});},methods: {...mapActions(['fetchUser', 'logout', 'fetchGroups']),formatDate() {return getCurrentDateTime();},kickopen(item) {this.name = item.namethis.toid = item.toidif (!item.isMe) {this.$refs.popupkick.open()}},getGroupOwner(id) {//接口 group 提交id 獲取到群的信息const token = uni.getStorageSync('token');return new Promise((resolve, reject) => {uni.request({url: `${config.apiBaseUrl}/group`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {id: id},success: (res) => {resolve(res)},fail: (err) => {reject(err)}});})},async widthdrawRow(sn) {const token = uni.getStorageSync('token');if (!token) return;try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/withdraw`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {sn: sn}});if (error) {throw new Error(`Request failed with error: ${error}`);}if (response.data.code === 0) {return true;} else {return false;}} catch (error) {return false;}},adduserTogroup() {this.isPopupOpen=falseuni.navigateTo({url: '/pages/index/addfriend?groupId=' + this.tid});},kick(type) {//將用戶踢出去if (this.group_owner_id != this.fid) {//這樣才能踢	if (type == 'kick') {this.kickUser(this.name)} else {//拉黑this.kickUser(this.name, 'black')//再拉黑}} else {uni.showToast({title: '不能對自己操作'})}},detail() {uni.navigateTo({url: '/pages/index/about?id=' + this.to_id});},groupdetail() {let groupid = this.groupName.replace('g_', '')if (this.type == 'group') {uni.navigateTo({url: '/pages/index/groupdetail?id=' + groupid});} else {uni.navigateTo({url: '/pages/index/about?id=' + this.to_id});}},async quitgroup() {console.log(this.group_owner_id)console.log(this.user.id)if (this.group_owner_id == this.user.id) {//主人不能退群uni.showToast({title: '主人不能退群'})return}let groupid = this.groupName.replace('g_', '')//調用接口退出 接口名為leavgroup 	const token = uni.getStorageSync('token');if (!token) return;try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/leavgroup`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {groupid}});if (error) {throw new Error(`Request failed with error: ${error}`);}console.log(response)if (response.data.code === 0) {uni.navigateTo({url: '/pages/index/friends'})return true;} else {return false;}} catch (error) {return false;}},onPopupChange() {if (this.isPopupOpen == true) {this.isPopupOpen = false;}},playVoice(url) {// 創(chuàng)建音頻對象const audio = new Audio(url);// 播放音頻audio.play().then(() => {console.log('音頻開始播放');}).catch((error) => {console.error('音頻播放失敗:', error);});// 監(jiān)聽音頻播放結束事件audio.onended = () => {console.log('音頻播放結束');};},onPopupAudioChange() {if (this.isPopupOpen == true) {this.isPopupOpen = false;}this.recordingPath = '';},audio() {this.$refs.popup.close();this.$refs.popupAudio.open();this.isPopupOpen = true;},exitchat() {this.$refs.popupAudio.close();},async 	startRecording() {try {if(this.isRecording){uni.showToast({title: '正在錄音中',icon: 'none',duration: 2000});return;}const stream = await navigator.mediaDevices.getUserMedia({ audio: true });this.mediaRecorder = new MediaRecorder(stream);//console.log(this.mediaRecorder);this.mediaRecorder.ondataavailable = (event) => {this.audioChunks.push(event.data);};this.mediaRecorder.onstop  = async () => {const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });const url = URL.createObjectURL(audioBlob);this.selectedFilePath = url;// 創(chuàng)建一個提示框const confirmResult = await new Promise((resolve) => {uni.showModal({title: '錄音完成',content: '是否上傳錄音?',confirmText: '上傳',cancelText: '取消',success: (res) => {resolve(true);}});});// 如果用戶選擇取消,則不繼續(xù)處理if (!confirmResult) {this.audioChunks = [];this.isRecording = false;return;}else{this.uploadAvatar('audio');}this.isPopupOpen=false;this.isRecording=false;// 清理本地聲音stream.getTracks().forEach(track => track.stop());URL.revokeObjectURL(url);};this.mediaRecorder.start();this.isRecording = true;} catch (error) {console.error('獲取麥克風權限失敗:', error);}},async stopRecording() {//console.log('停止錄音')if (this.mediaRecorder) {this.mediaRecorder.stop();this.isRecording = false;this.popupAudio=false;}else{uni.showToast({title: '沒有錄音',icon: 'none'});}},uploadAudio(audioBlob) {const formData = new FormData();formData.append('audio', audioBlob, 'recorded_audio.wav');console.log(URL.createObjectURL(audioBlob))const token = uni.getStorageSync('token');uni.uploadFile({url: `${config.apiBaseUrl}/upload`,filePath: URL.createObjectURL(audioBlob),name: 'avatar',header: {Authorization: `Bearer ${token}`},// formData: formData,success: (uploadFileRes) => {const response = JSON.parse(uploadFileRes.data);if (response.code == 0) {const avatarUrl = response.data;this.sendMessage(avatarUrl, 'audio');}},fail: (err) => {//console.error('上傳失敗:', err);console.error('Failed to upload avatar:', error);uni.showToast({title: '上傳失敗',icon: 'none'});}});},playRecording() {if (this.recordingPath) {const innerAudioContext = uni.createInnerAudioContext();innerAudioContext.src = this.recordingPath;innerAudioContext.onPlay(() => {console.log('開始播放錄音');});innerAudioContext.onError((res) => {console.error('播放錄音失敗:', res);});innerAudioContext.play();} else {uni.showToast({title: '沒有可播放的錄音',icon: 'none'});}},upsong() {const token = uni.getStorageSync('token');uni.uploadFile({url: `${config.apiBaseUrl}/upload`,filePath: this.selectedFilePath,name: 'avatar',header: {Authorization: `Bearer ${token}`},success: async (uploadFileRes) => {const response = JSON.parse(uploadFileRes.data);if (response.code == 0) {const avatarUrl = response.data;this.sendMessage(avatarUrl, type);}},fail: (error) => {console.error('Failed to upload avatar:', error);uni.showToast({title: '上傳失敗',icon: 'none'});}});  },more() {this.$refs.popup.open();this.isPopupOpen = true;},openCamera() {if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {// 創(chuàng)建視頻元素const video = document.createElement('video');video.srcObject = stream;video.autoplay = true;// 創(chuàng)建容器const container = document.createElement('div');container.style.position = 'fixed';container.style.top = '0';container.style.left = '0';container.style.width = '100%';container.style.height = '100%';container.style.backgroundColor = 'rgba(0,0,0,0.8)';container.style.zIndex = '9999';container.appendChild(video);document.body.appendChild(container);// 創(chuàng)建錄制器const mediaRecorder = new MediaRecorder(stream);let chunks = [];mediaRecorder.ondataavailable = (e) => {chunks.push(e.data);};mediaRecorder.onstop = () => {const blob = new Blob(chunks, { type: 'video/webm' });chunks = [];const videoUrl = URL.createObjectURL(blob);this.selectedFilePath = videoUrl;this.uploadAvatar('video');};// 開始錄制mediaRecorder.start();// 添加上傳按鈕const uploadButton = document.createElement('button');uploadButton.textContent = '停止錄制并上傳';uploadButton.style.position = 'absolute';uploadButton.style.bottom = '10px';uploadButton.style.left = '50%';uploadButton.style.transform = 'translateX(-50%)';uploadButton.onclick = () => {mediaRecorder.stop();stream.getTracks().forEach(track => track.stop());document.body.removeChild(container);};container.appendChild(uploadButton);}).catch((error) => {console.error('無法訪問攝像頭:', error);uni.showToast({title: '無法訪問攝像頭',icon: 'none'});});} else {uni.showToast({title: '您的設備不支持攝像頭',icon: 'none'});}// if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {// 			navigator.mediaDevices.getUserMedia({ video: true })// 				.then((stream) => {// 					// 創(chuàng)建一個 video 元素來顯示攝像頭畫面// 					const video = document.createElement('video');// 					video.srcObject = stream;// 					video.autoplay = true;// 					// 創(chuàng)建一個容器來放置 video 元素// 					const container = document.createElement('div');// 					container.style.position = 'fixed';// 					container.style.top = '0';// 					container.style.left = '0';// 					container.style.width = '100%';// 					container.style.height = '100%';// 					container.style.backgroundColor = 'rgba(0,0,0,0.8)';// 					container.style.zIndex = '9999';// 					container.appendChild(video);// 					document.body.appendChild(container);// 					// 創(chuàng)建一個 canvas 元素用于捕獲視頻幀// 					const canvas = document.createElement('canvas');// 					// 添加一個按鈕來關閉攝像頭并上傳圖片// 					const closeButton = document.createElement('button');// 					closeButton.textContent = '拍照并上傳';// 					closeButton.style.position = 'absolute';// 					closeButton.style.bottom = '10px';// 					closeButton.style.left = '50%';// 					closeButton.style.transform = 'translateX(-50%)';// 					closeButton.onclick = () => {// 						// 捕獲當前視頻幀// 						canvas.width = video.videoWidth;// 						canvas.height = video.videoHeight;// 						canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);// 						// 將 canvas 轉換為 Blob// 						canvas.toBlob((blob) => {// 							// 停止所有視頻軌道// 							stream.getTracks().forEach(track => track.stop());// 							// 移除容器// 							document.body.removeChild(container);// 							// 創(chuàng)建一個臨時的 URL// 							const imageUrl = URL.createObjectURL(blob);// 							// 將Blob轉換為File對象,并設置.mp4后綴// 							//const file = new File([blob], 'captured_video.mp4', { type: 'video/mp4' });// 							// 創(chuàng)建新的臨時URL// 							// 設置 selectedFilePath 并調用 uploadAvatar// 							this.selectedFilePath = imageUrl;// 							this.uploadAvatar('video');// 							// 清理臨時 URL// 							URL.revokeObjectURL(imageUrl);// 						}, 'image/jpeg');// 					};// 					container.appendChild(closeButton);// 				})// 				.catch((error) => {// 					console.error('無法訪問攝像頭:', error);// 					uni.showToast({// 						title: '無法訪問攝像頭',// 						icon: 'none',// 						duration: 2000// 					});// 				});// 		} else {// 			uni.showToast({// 				title: '您的設備不支持攝像頭訪問',// 				icon: 'none',// 				duration: 2000// 			});// 		}},withdraw(item) {let _ = this;const currentTime = Date.now();const messageTime = parseInt(item.time);const oneMinute = config.minute; // 60 * 1000 millisecondsif (currentTime < (messageTime + oneMinute)) {uni.showModal({title: '提示',content: '確認刪除該條信息嗎?',success: function(res) {if (res.confirm) {// 執(zhí)行確認后的操作if (_.canwithdraw(item)) {const messageData = {sn: uuidv4(),group_name: _.groupName,avatar: _.user.avatar_url,content: item.sn,user_name: _.user.username,type: 'widthdraw',fid: _.user.id,tid: _.tid,created_at: _.getCurrentTimeToMinute(),receiver_type: _.receiver_type};_.socket.emit('sendMessage', messageData);} else {uni.showToast({title: '超過一分鐘不能撤回',icon: 'none'});}} else {// 執(zhí)行取消后的操作}}});}},canwithdraw(item) {const currentTime = Date.now();const messageTime = parseInt(item.time);const oneMinute = config.minute; // 60 * 1000 millisecondsif (currentTime > (messageTime + oneMinute)) {return false;} else {return true;}},getCurrentTimeToMinute() {const now = new Date();// 使用 Intl.DateTimeFormat 格式化日期和時間const dateFormatter = new Intl.DateTimeFormat('default', {year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',minute: '2-digit',hour12: false});// 格式化日期時間并返回return dateFormatter.format(now).replace(',', '');},async checkFriend(id) {const token = uni.getStorageSync('token');if (!token) return;let data = {id};try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/checkFriend`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {Id: id}});if (error) {throw new Error(`Request failed with error: ${error}`);}if (response.data.code === 0) {return true;} else {return false;}} catch (error) {return false;}},joinGroup() {this.socket.emit('joinGroup', {groupName: this.groupName,userName: this.user.username,userId: this.user.id});},tapTo(state) {let message = this.inputValue;if (message == '') {uni.showToast({title: '請輸入聊天內容',icon: 'error'});return;}this.sendMessage(message);},getInput(e) {this.inputValue = e.detail.value;},initChatLog() {console.log('-initChatLog-')let _ = this;this.list = [];//接口 group 提交id 獲取到群的信息const token = uni.getStorageSync('token');return new Promise((resolve, reject) => {uni.request({url: `${config.apiBaseUrl}/getMessages`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {receiver_type: _.receiver_type,tid: _.to_id   // 修復Bug, 原來這里寫的是 _.tid},success: (res) => {resolve(res)console.log('-getMessages-')console.log(res.data.data.messages)this.list = res.data.data.messagesthis.list.forEach((item, index) => {this.list[index].isMe = item.fid == this.user.id ? true :false;this.list[index].toid = item.fid});},fail: (err) => {reject(err)}});})},async sendMessage(message, type = 'text') {this.$refs.popup.close();const messageData = {sn: uuidv4(),group_name: this.groupName,avatar: this.user.avatar_url,content: message,user_name: this.user.username,type: type,fid: this.user.id,tid: this.to_id, // 原來this.tid寫錯了  created_at: this.getCurrentTimeToMinute(),receiver_type: this.receiver_type};this.socket.emit('sendMessage', messageData);this.inputValue = '';if (type == 'image' || type == 'audio' || type == 'video' || type == 'text') {const token = uni.getStorageSync('token');try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/addmessage`,method: 'POST',header: {Authorization: `Bearer ${token}`},data: messageData});if (error) {throw new Error(`Request failed with error: ${error}`);}} catch (error) {}}this.$nextTick(() => {this.setScrollTop();});},async kickUser(name, type = 'kick') {console.log("groupname", this.groupName)console.log("name", name)console.log("type", type)if (type == 'kick') {this.socket.emit('kickUser', {groupName: this.type == 'group' ? this.groupName : this.groupName.replace('g_', ''),userName: name});} else {this.socket.emit('kickUser', {groupName: this.type == 'group' ? this.groupName : this.groupName.replace('g_', ''),userName: name});//拉黑let group_id = this.groupName.replace('g_', '')if (this.type != 'group') {group_id = 0}//調用black接口進行拉黑,攔黑完成讓界面跳到friendsconst token = uni.getStorageSync('token');try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/black`,method: 'POST',header: {Authorization: `Bearer ${token}`},data: {name,group_id}});if (error) {throw new Error(`Request failed with error: ${error}`);}if (response.data.data.code == 0) {if (this.type == 'user') {uni.navigateTo({url: '/pages/index/friends'})}}} catch (error) {}}},setScrollTop() {this.$nextTick(() => {let query = uni.createSelectorQuery().in(this);query.select('.scroll-view').boundingClientRect((rect) => {if (rect) {this.scrollHeight = rect.height;}}).exec();});},chooseFile() {// 檢查是否為PC端const isPC = /Windows|Mac|Linux/.test(navigator.userAgent);if (isPC) {// PC端,調用攝像頭拍照if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {// 創(chuàng)建視頻元素const video = document.createElement('video');video.srcObject = stream;video.autoplay = true;// 創(chuàng)建容器const container = document.createElement('div');container.style.position = 'fixed';container.style.top = '0';container.style.left = '0';container.style.width = '100%';container.style.height = '100%';container.style.backgroundColor = 'rgba(0,0,0,0.8)';container.style.zIndex = '9999';container.appendChild(video);document.body.appendChild(container);// 添加拍照按鈕const captureButton = document.createElement('button');captureButton.textContent = '拍照';captureButton.style.position = 'absolute';captureButton.style.bottom = '10px';captureButton.style.left = '30%';captureButton.style.transform = 'translateX(-50%)';captureButton.onclick = () => {// 創(chuàng)建canvas并捕獲當前視頻幀const canvas = document.createElement('canvas');canvas.width = video.videoWidth;canvas.height = video.videoHeight;canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);// 將canvas轉換為Blobcanvas.toBlob((blob) => {// 停止所有視頻軌道stream.getTracks().forEach(track => track.stop());// 移除容器document.body.removeChild(container);// 創(chuàng)建臨時URL并上傳const imageUrl = URL.createObjectURL(blob);this.selectedFilePath = imageUrl;this.uploadAvatar('image');// 清理臨時URLURL.revokeObjectURL(imageUrl);}, 'image/jpeg');};container.appendChild(captureButton);// 添加取消按鈕const cancelButton = document.createElement('button');cancelButton.textContent = '取消';cancelButton.style.position = 'absolute';cancelButton.style.bottom = '10px';cancelButton.style.left = '70%';cancelButton.style.transform = 'translateX(-50%)';cancelButton.onclick = () => {// 停止所有視頻軌道stream.getTracks().forEach(track => track.stop());// 移除容器document.body.removeChild(container);// 繼續(xù)執(zhí)行選擇文件的邏輯this.showFileChooseOptions();};container.appendChild(cancelButton);}).catch((error) => {console.error('無法訪問攝像頭:', error);uni.showToast({title: '無法訪問攝像頭',icon: 'none'});// 如果無法訪問攝像頭,繼續(xù)執(zhí)行選擇文件的邏輯this.showFileChooseOptions();});} else {uni.showToast({title: '您的設備不支持攝像頭',icon: 'none'});// 如果設備不支持攝像頭,繼續(xù)執(zhí)行選擇文件的邏輯this.showFileChooseOptions();}} else {// 非PC端,直接執(zhí)行選擇文件的邏輯this.showFileChooseOptions();}},showFileChooseOptions(){uni.showActionSheet({itemList: ['拍照', '從相冊選擇'],success: (res) => {if (res.tapIndex === 0) {this.takePhoto();} else if (res.tapIndex === 1) {this.selectImage();}},fail: (error) => {console.error('Failed to show action sheet:', error);uni.showToast({title: '操作失敗',icon: 'none'});}});},takePhoto() {uni.chooseImage({count: 1,sourceType: ['camera'],success: async (res) => {this.selectedFilePath = res.tempFilePaths[0];await this.uploadAvatar('image');},fail: (error) => {console.error('Failed to take photo:', error);uni.showToast({title: '拍照失敗',icon: 'none'});}});},selectImage() {uni.chooseImage({count: 1,sourceType: ['album'],success: async (res) => {this.selectedFilePath = res.tempFilePaths[0];await this.uploadAvatar('image');},fail: (error) => {console.error('Failed to select image:', error);uni.showToast({title: '選擇圖片失敗',icon: 'none'});}});},previewImage(url) {uni.previewImage({urls: [url] // 需要預覽的圖片http鏈接列表});},async uploadAvatar(type) {if (!this.selectedFilePath) {uni.showToast({title: '請選擇文件',icon: 'none'});return;}const token = uni.getStorageSync('token');uni.uploadFile({url: `${config.apiBaseUrl}/upload`,filePath: this.selectedFilePath,name: 'avatar',header: {Authorization: `Bearer ${token}`},success: async (uploadFileRes) => {const response = JSON.parse(uploadFileRes.data);if (response.code == 0) {const avatarUrl = response.data;this.sendMessage(avatarUrl, type);}},fail: (error) => {console.error('Failed to upload avatar:', error);uni.showToast({title: '上傳失敗',icon: 'none'});}});},copyBtnClick(data) {handleClipboard( // 這是 實現(xiàn)向剪切板 寫入內容的代碼, data 就是傳入的要寫入剪切板的內容// 寫入剪切板data,  event,() => {uni.showToast({title: '已復制到剪切板',});},() => {uni.showToast({title: '復制失敗',});});},formatMessage(content) {// Detect URLs and format them as linksconst urlRegex = /(https?:\/\/[^\s]+)/g;content = content.replace(urlRegex, '<a href="$1" target="_blank" style="color:blue;">$1</a>');return content.replace(/\n/g, '<br>');},detectCode(content) {// Basic check to see if the content is likely code (this can be improved)const codeKeywords = ['function', 'const', 'let', 'var', 'if', 'else', '{', '}', '=', '=>'];return codeKeywords.some(keyword => content.includes(keyword)) || /[<>&]/.test(content);},escapeHtml(content) {// Escape HTML to prevent it from being rendered as actual HTMLreturn content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");}}};
</script>
<style lang="scss" scoped>@import url('static/iconfont.css');.base-btn {position: fixed;width: 100%;height: 50px;bottom: var(--window-bottom);left: 0;justify-content: space-between;background-color: #ffffff;transition: bottom 0.3s;}.base-btn-popup-open {bottom: 200rpx;/* 調整為 popup 高度 */}.base-con {margin-top: 7.5px;display: flex;height: inherit;align-items: center;justify-content: space-between;}.send-image {width: 35px;line-height: 35px;background-color: #ffb967;border-radius: 50%;text-align: center;color: #ffffff;font-size: 30rpx;}.input-text {width: 58%;height: 35px;background-color: #f2f2f2;border-radius: 8px;padding: 0 15px;}.send-input {width: 64px;line-height: 35px;text-align: center;background-color: #ffb967;border-radius: 8px;color: #ffffff;}.scroll-view,.base-con {margin: 0 15px;}.avatar {width: 32px;height: 32px;border-radius: 50%;float: left;margin-top: 20px;}.avatar-right {margin-right: 10px;}.message-box {max-width: 76%;display: inline-block;word-wrap: break-word;/* 控制消息框換行 */}.message {font-size: 30rpx;background-color: #e6e6e6;padding: 10px;float: left;border-radius: 8px;overflow: hidden;word-break: break-all;white-space: pre-wrap;margin-top: 10px;width: 100%;}.message_img {font-size: 0rpx;background-color: lightgray;padding: 10px;float: left;border-radius: 8px;overflow: hidden;word-break: break-all;white-space: pre-wrap;margin-top: 5px;}.message-image {width: 80px;height: 130px;padding: 15px 0;border-radius: 8px;overflow: hidden;}.news-box::after {content: '';display: block;clear: both;}.news-box:last-child .message {margin-bottom: 20px;}.is-me {float: right;margin-left: 10px;}.message-type {text-align: center;color: #aaa;/* 字體顏色變淡 */font-size: 20rpx;/* 字體小一號 */margin-top: 10px;}.group-box {color: #727172;/* 字體顏色變淡 */font-size: 26rpx;/* 字體小一號 */margin: 6px 0 0 6px;}.group-member {margin-right: 4px;}.popup-content {display: flex;justify-content: center;/* 居中對齊內容 */align-items: center;/* 垂直居中對齊 */}.popup-items {display: flex;width: 100%;flex-wrap: wrap;/* 允許換行 */justify-content: space-around;/* 平均分配空間 */padding: 10rpx;/* 可選的內邊距 */}.popup-item {flex: 1 1 10%;/* 每個圖片占據(jù) 20% 的寬度,支持換行 */display: flex;flex-direction: column;/* 垂直布局 */justify-content: center;align-items: center;margin: 5rpx;/* 圖片間距 */}.popup-image {width: 80%;/* 圖片寬度占父容器的 80% */height: auto;/* 高度自動,以保持寬高比 */object-fit: cover;/* 確保圖片在框中完全填充 */}.username {font-size: 20rpx;color: #666;margin-top: 5px;text-align: center;}
</style>
http://aloenet.com.cn/news/40696.html

相關文章:

  • 中國建設網(wǎng)站齊齊哈爾市中國唯一沒有疫情的地方
  • 性用品網(wǎng)商做的最好的網(wǎng)站下列哪些店鋪適合交換友情鏈接
  • 兩性做受技巧視頻網(wǎng)站廣告聯(lián)盟
  • wordpress多重標簽連云港seo
  • 建設工程168類似的網(wǎng)站百度下載免費
  • 免費的ppt網(wǎng)站推薦北京優(yōu)化seo排名
  • 2019建設銀行招聘網(wǎng)站sem競價推廣公司
  • 做視頻網(wǎng)站要注意什么電工培訓課程
  • 做外貿需掌握的網(wǎng)站杭州seo博客
  • 設計本官方網(wǎng)站廣告廣告關鍵詞查詢
  • 成都58手機微信網(wǎng)站建設名錄青島快速排名
  • 朝陽網(wǎng)絡 網(wǎng)站建設痘痘如何去除效果好
  • 海爾商務網(wǎng)站建設企業(yè)網(wǎng)站是什么
  • wordpress seo插件中文版廣州網(wǎng)絡推廣seo
  • 南山做網(wǎng)站公司seo外鏈工具下載
  • php 網(wǎng)站 模板百度一下百度搜索百度
  • 上海設計網(wǎng)站開發(fā)日本疫情最新數(shù)據(jù)
  • 購物網(wǎng)站難做嗎google seo怎么優(yōu)化
  • 公司網(wǎng)站設計需要什么百度優(yōu)化點擊軟件
  • 怎么做網(wǎng)站的跳轉seo查詢外鏈
  • 在線制作logo設計百度seo排名優(yōu)化系統(tǒng)
  • 求職網(wǎng)站開發(fā)十大職業(yè)資格培訓機構
  • 阿里云一鍵安裝wordpress百度快照優(yōu)化培訓班
  • 長春公司做網(wǎng)站如何在百度提交自己的網(wǎng)站
  • 學校門戶網(wǎng)站建設工作自己搭建一個網(wǎng)站
  • 企業(yè)郵箱注冊申請需要多少錢鄭州網(wǎng)站優(yōu)化外包
  • 做網(wǎng)上水果網(wǎng)站的調查百度sem代運營
  • wordpress網(wǎng)站反應慢seo學習網(wǎng)站
  • 無錫網(wǎng)站建設公司排名網(wǎng)絡推廣包括哪些
  • 網(wǎng)站空間 php怎么在百度上發(fā)布信息廣告