| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225 |
- <script>
- import {
- getDictByKey,
- getAppVersion,
- getRealLinkDomainName
- } from '@/api/common';
- //参考文档 插件市场 https://ext.dcloud.net.cn/plugin?id=741
- import {
- appCheckUdate,
- openDownload
- } from '@/utils/APPUpdate.js';
- import {
- getUserInfo,
- getPushLogRead
- } from '@/api/user';
- import {
- healthButlerPop
- } from '@/utils/healthButlerPop.js';
- // import store from "@/store";
- import {
- mapGetters,
- mapActions
- } from 'vuex';
- import IMSDK, {
- IMMethods,
- MessageReceiveOptType,
- MessageType,
- SessionType
- } from 'openim-uniapp-polyfill';
- import {
- config
- } from '@/pages_im/common/config';
- import {
- getDbDir,
- Igexin,
- toastWithCallback
- } from '@/pages_im/util/common.js';
- import {
- conversationSort,
- secFormat,
- callingModule,
- meetingModule,
- parseMessageByType,
- prepareConversationState
- } from '@/pages_im/util/imCommon';
- import {
- PageEvents,
- UpdateMessageTypes,
- CustomType,
- ContactChooseTypes
- } from '@/pages_im/constant';
- import {
- openImLoginApi
- } from '@/pages_im/api/imBll';
- import NotificationUtil from '@/pages_im/util/notification';
- import newMessage from '@/pages_im/static/audio/newMessage.wav';
- import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
- let cacheConversationList = [];
- let updateDownloadTask = null;
- let notificationIntance = null;
- let pausing = false;
- let innerAudioContext;
- let notification;
- let uPushPlugin;
- // #ifdef APP-PLUS
- import permision1 from '@/utils/permission.js';
- uPushPlugin = uni.requireNativePlugin('DCloud-PushSound');
- notification = uni.requireNativePlugin('Tuoyun-OpenIMSDK-Notification');
- // #endif
- import {
- getTlsSig
- } from '@/api/common.js';
- import {
- qconfig
- } from './utils/config';
- import {
- premissionCheck
- } from '@/js_sdk/wa-permission/permission.js';
- import {
- updateMsgDot
- } from '@/utils/common.js';
- import {
- getImAdminToken
- } from '@/pages_im/api/imApi';
- import {
- ar
- } from 'date-fns/locale';
- let healthTimer = null;
- let tSeconds = 0;
- const healthSeconds = 180;
- let offlineMsg = null;
- let offlineHandleNewMsg = null;
- const baseUrl = 'https://userapp.zkhj6.com'
- export default {
- globalData: {
- wsUrl: 'ws://webim.zkhj6.com',
- danmuWSUrl: 'wss://webim.zkhj6.com',
- aiWSUrl: 'ws://webim.zkhj6.com',
- kfurl: 'https://work.weixin.qq.com/kfid/kfc3731c5008ebd8906', //企业微信客服链接
- corpId: 'ww70ac72e824957fc9', //客服企业id
- miniprogamId: 'gh_5db2859e4e72',
- shareCorpId: '', // 分享企业id
- shareSchema: "", // 应用跳转标识,显示在具体应用下的 Schema字段
- shareAgentid: "", // 企业微信管理后台 应用唯一标识。显示在具体应用下的 AgentId字段
- shareAppid_gh: "", // 必须是应用关联的小程序,注意要有@app后缀
- privacyPolicy: baseUrl + "/web/privacyPolicy", //隐私政策
- userAgreement: baseUrl + "/web/userAgreement", //用户协议
- baseUrl: baseUrl,
- activityId: 1,
- },
- onLaunch: function(options) {
- uni.getClipboardData({
- success: (res) => {
- const resutl = this.getUrlParam(res.data, 'android_schema')
- if (resutl) {
- uni.navigateTo({
- url: resutl
- })
- }
- }
- });
- //设置字体大小
- let fontsize = uni.getStorageSync('fontSize');
- if (fontsize) {
- //store.commit("timStore/setScaleFontSize", fontsize);
- uni.setStorageSync('fontSize', fontsize);
- } else {
- let scale = this.getSystemFontScale();
- let oriFontSize = 18;
- fontsize = oriFontSize * scale;
- if (fontsize < oriFontSize) {
- fontsize = oriFontSize;
- }
- if (fontsize < 16) {
- fontsize = 16;
- }
- if (fontsize >= 21) {
- fontsize = 21;
- }
- uni.setStorageSync('fontSize', fontsize);
- }
- //设置im字体
- let RootFontSize = uni.getStorageSync('RootFontSize');
- if (!RootFontSize) {
- uni.setStorageSync('RootFontSize', "24px");
- this.$store.commit('user/SET_ROOT_FONT_SIZE', "24px");
- }
- uni.removeStorageSync('openUrl');
- this.initOpenIm();
- if (this.$isLogin()) {
- uni.setStorageSync("onLaunch", 1);
- //this.getClipboardData();
- }
- let that = this;
- uni.$on('refreshIM', () => {
- if (that.$isLogin()) {
- that.openImLogin();
- }
- });
- // #ifdef APP-PLUS
- uni.$on('showHealthButler', () => {
- if (plus.runtime.channel == 'baidu' || plus.runtime.channel == 'yybadv' || plus.runtime
- .channel == 'yybadv1') {
- that.runTimer();
- }
- });
- //离线推送
- this.handlerLaunchMsg();
- uni.onPushMessage((res) => { //unipush2.0 应用处于激活 监听消息推送
- //console.log("qxj onPushMessage",res);
- this.handlePushMessage(res);
- this.$updateMsgDot();
- });
- //#endif
- },
- onLoad() {
- },
- onShow() {
- this.getDictByKeyFun()
- this.geth5Path();
- var that = this;
- if (that.$isLogin()) {
- //that.$getRegistrationID('update');
- }
- // #ifdef APP-PLUS
- if (plus.runtime.isAgreePrivacy()) {
- //this.$getRegistrationID();
- if (plus.runtime.channel == 'baidu' || plus.runtime.channel == 'yybadv' || plus.runtime.channel ==
- 'yybadv1') {
- this.runTimer();
- }
- }
- if (uni.$u.os() === 'android') {
- this.checkUpdateApp();
- IMSDK.asyncApi(IMSDK.IMMethods.SetAppBackgroundStatus, IMSDK.uuid(), false);
- meetingModule?.onListenerAppBackground(false);
- }
- var args = plus.runtime.arguments;
- uni.setStorageSync("appIsOnShow", 1);
- if (args) {
- // 处理args参数,如直达到某新页面等
- if (args == "rtlive://course") {
- uni.switchTab({
- url: '/pages/course/index'
- });
- } else if (args == "rtlive://livingApp") {
- uni.switchTab({
- url: '/pages/course/video/living-app'
- });
- } else {
- let url = ''
- if (args.indexOf("rtlive://pagesApp") != -1) { // 打开对应pages
- url = args.replace("rtlive://pagesApp?pagesUrl=", "");
- url = decodeURIComponent(url);
- } else if (args.indexOf("rtlive://courseAnswer") != -1) { // 看课
- url = args.replace("rtlive://courseAnswer", "");
- url = "/pages/courseAnswer/index" + url;
- } else if (args.indexOf("rtlive://") != -1 && url) {
- uni.setStorageSync("openUrl", url)
- if (this.$isLogin()) {
- uni.navigateTo({
- url: url,
- success: function(res) {
- uni.removeStorageSync("openUrl")
- plus.runtime.arguments = ''
- }
- });
- }
- } else if (args.indexOf("contentType") != -1) { //unipush2.0 App打开状态点击通知
- let newServerMsg = JSON.parse(args);
- let serverMsgID = uni.getStorageSync('serverMsgID');
- if (serverMsgID != newServerMsg.data.serverMsgID) {
- uni.$u.throttle(() => that.notifyGoToChat(newServerMsg), 2000);
- uni.setStorageSync('serverMsgID', newServerMsg.data.serverMsgID);
- }
- } else if (args.indexOf("messageId") != -1) { //oppo离线推送
- offlineMsg = args;
- } else if (args.indexOf("rtlive://course") != -1) {
- url = args.replace("rtlive://course", "");
- url = "/pages/course/info" + url;
- }
- }
- }
- //#endif
- },
- onHide() {
- uni.removeStorageSync('onLaunch');
- uni.removeStorageSync('appIsOnShow');
- if (uni.$u.os() === 'android') {
- IMSDK.asyncApi(IMSDK.IMMethods.SetAppBackgroundStatus, IMSDK.uuid(), true);
- meetingModule?.onListenerAppBackground(true);
- }
- },
- computed: {
- ...mapGetters([
- 'storeConversationList',
- 'storeCurrentConversation',
- 'storeCurrentUserID',
- 'storeSelfInfo',
- 'storeRecvFriendApplications',
- 'storeRecvGroupApplications',
- 'storeHistoryMessageList',
- 'storeIsSyncing',
- 'storeGroupList'
- ]),
- contactBadgeRely() {
- return {
- recvFriendApplications: this.storeRecvFriendApplications,
- recvGroupApplications: this.storeRecvGroupApplications,
- userKey: this.storeCurrentUserID
- };
- }
- },
- methods: {
- ...mapActions('message', ['pushNewMessage', 'updateOneMessage', 'updateQuoteMessageRevoke',
- 'updateMessageNicknameAndFaceUrl'
- ]),
- ...mapActions('conversation', ['updateCurrentMemberInGroup']),
- ...mapActions('contact', [
- 'updateFriendInfo',
- 'pushNewFriend',
- 'updateBlackInfo',
- 'pushNewBlack',
- 'pushNewGroup',
- 'updateGroupInfo',
- 'pushNewRecvFriendApplition',
- 'updateRecvFriendApplition',
- 'pushNewSentFriendApplition',
- 'updateSentFriendApplition',
- 'pushNewRecvGroupApplition',
- 'updateRecvGroupApplition',
- 'pushNewSentGroupApplition',
- 'updateSentGroupApplition'
- ]),
- getUrlParam(paramStr, key) {
- // 1. 将参数字符串拆分为键值对数组
- const paramPairs = paramStr.split('&');
- let result = '';
- // 2. 遍历查找目标参数
- for (const pair of paramPairs) {
- const [paramKey, paramValue] = pair.split('=');
- // 匹配目标参数名
- if (paramKey == key && paramValue) {
- // 3. 对参数值进行URL解码(处理%2F、%3F等编码字符)
- result = decodeURIComponent(paramValue);
- break;
- }
- }
- return result;
- },
- async getDictByKeyFun() {
- let data = {
- key: 'app_pay_config'
- }
- const res = await getDictByKey(data)
- if (res.code == 200 && res.data && res.data.length > 0 && res.data[0].dictValue) {
- getApp().globalData.miniprogamId = res.data[0].dictValue
- }
- },
- getCid() {
- document.addEventListener('plusready', function() {
- console.log("plusready");
- //页面加载时触发
- plus.push.getClientInfoAsync((info) => {
- let cid = info["clientid"];
- console.log("qxj getClientInfoAsync info:" + JSON.stringify(info));
- });
- }, false);
- },
- handlePushMessage(res) { //unipush2.0
- const that = this;
- console.log("qxj handlePushMessage", res);
- if (res.type == 'click') { //unipush2.0在线推送 如果需要跳转app内指定页面,则自己实现下方的跳转代码。
- if (this.$isLogin()) {
- const pages = getCurrentPages();
- const url = pages[pages.length - 1];
- const isOnLaunch = uni.getStorageSync('onLaunch');
- // 判断前一个页面路径是一样
- const payloadData = JSON.parse(res.data.payload.data);
- const flag = pages && url.route && res.data.payload.url.indexOf(url.route);
- const isIM = payloadData.type != undefined && payloadData.type == 'im';
- if (isIM) {
- if (isOnLaunch && isOnLaunch == 1) {
- //offlineMsg=res.data.payload;
- uni.removeStorageSync('onLaunch');
- } else {
- uni.$u.throttle(() => that.notifyGoToChat(payloadData), 2000);
- }
- } else {
- if (isOnLaunch && isOnLaunch == 1) {
- uni.showLoading({
- title: '处理中..'
- });
- setTimeout(() => {
- uni.hideLoading();
- if (flag == -1) {
- uni.navigateTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- } else {
- uni.redirectTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- }
- }, 1000);
- } else {
- uni.hideLoading();
- if (flag == -1) {
- uni.navigateTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- } else {
- uni.redirectTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- }
- }
- }
- }
- }
- if (res.type == 'receive') { //监听在线推送消息,若云函数设置了 "force_notification":true,则不会触发此 receive。
- const pages = getCurrentPages();
- const url = pages[pages.length - 1];
- if (url && (url.route != "pages_im/pages/conversation/chating/index")) {
- // 检查应用是否在前台
- const appIsOnShow = uni.getStorageSync('appIsOnShow');
- //if(!!appIsOnShow){ // 应用在前台,处理消息但不显示通知
- uni.createPushMessage({
- title: res.data.title,
- content: res.data.content,
- payload: res.data.payload,
- when: new Date(),
- icon: "",
- sound: 'system', // 默认值为system
- category: res.data.category,
- success: () => {
- console.log('创建在线推送消息成功: ');
- this.$store.commit('newMsg/SET_UPDATATIME', new Date().getTime());
- },
- fail: (err) => {
- console.log('创建在线推送消息失败: ', err);
- }
- });
- //}
- plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
- if (widgetInfo.visible) {
- // 应用在前台,处理消息但不显示通知
- uni.createPushMessage({
- title: res.data.title,
- content: res.data.content,
- payload: res.data.payload,
- sound: 'system', // 默认值为system
- category: res.data.category,
- success: () => {
- console.log('创建在线推送消息成功: ');
- this.$store.commit('newMsg/SET_UPDATATIME', new Date()
- .getTime());
- },
- fail: (err) => {
- console.log('创建在线推送消息失败: ', err);
- }
- });
- } else {
- // 应用在后台,可以显示通知(如果需要)
- }
- });
- }
- }
- },
- // 处理Launch信息
- handlerLaunchMsg() {
- let that = this;
- // 监听通知点击事件
- plus.push.addEventListener('click', function(msg) { //unipush2.0 离线推送 (小米)
- let newServerMsg = msg.payload;
- offlineMsg = msg;
- });
- // 获取启动时的通知
- plus.push.getClientInfoAsync(function(info) { //unipush2.0连离线推送/点击桌面启动 (小米)
- console.log("qxj getClientInfoAsync", info);
- if (info.id && info.id == "unipush") { //unipush1.0 荣耀离线推送
- offlineMsg = info;
- }
- if (info.title && info.content && info.payload) {
- uni.switchTab({
- url: 'pages_im/pages/conversation/conversationList/index'
- });
- }
- if (info.launch && info.launch.payload) {
- let newServerMsg = info.launch.payload;
- console.log('应用通过通知启动:', info);
- uni.switchTab({
- url: 'pages_im/pages/conversation/conversationList/index'
- });
- //uni.$u.throttle(() => that.notifyGoToChat(newServerMsg), 1000);
- }
- }, function(err) {
- });
- },
- getSystemFontScale: function() {
- let scale = 1;
- if (uni.getSystemInfoSync) {
- let systemInfo = uni.getSystemInfoSync();
- if (systemInfo.fontSizeSetting) {
- scale = systemInfo.fontSizeSetting / 16; // 16 是默认字体大小
- }
- }
- return scale;
- },
- adjustFontSize: function() {
- let scale = this.getSystemFontScale();
- let rootElement = document.documentElement;
- rootElement.style.fontSize = 16 * scale + 'px';
- },
- setGlobalIMlistener() {
- const kickHander = (message) => {
- toastWithCallback(message, () => {
- uni.removeStorage({
- key: 'IMToken'
- });
- uni.removeStorage({
- key: 'BusinessToken'
- });
- callingModule?.endCall();
- meetingModule?.endCall();
- Igexin.unbindAlias(this.storeCurrentUserID);
- uni.$emit('loginOut');
- // uni.$u.route({url: "/pages/login/index",type: "redirect"});
- });
- };
- let that = this;
- IMSDK.subscribe(IMSDK.IMEvents.OnKickedOffline, (data) => {
- kickHander('您的账号在其他设备登录,请重新登录!');
- setTimeout(() => {
- uni.clearStorage()
- that.$logout();
- }, 1000)
- //that.removeImData();
- //that.openImLogin();
- });
- IMSDK.subscribe(IMSDK.IMEvents.OnUserTokenExpired, (data) => {
- kickHander('您的登录已过期,请重新登录!');
- setTimeout(() => {
- uni.clearStorage()
- that.$logout();
- }, 1000)
- //that.removeImData();
- //that.openImLogin();
- });
- IMSDK.subscribe(IMSDK.IMEvents.OnUserTokenInvalid, (data) => {
- kickHander('您的登录已无效,请重新登录!');
- setTimeout(() => {
- uni.clearStorage()
- that.$logout();
- }, 1000)
- //that.removeImData();
- //that.openImLogin();
- });
- // sync
- const syncStartHandler = ({
- data
- }) => {
- this.$store.commit('user/SET_IS_SYNCING', true);
- this.$store.commit('user/SET_REINSTALL', data);
- };
- const syncProgressHandler = ({
- data
- }) => {
- this.$store.commit('user/SET_PROGRESS', data);
- };
- const syncFinishHandler = () => {
- this.$store.dispatch('conversation/getConversationList');
- this.$store.dispatch('contact/getFriendList');
- this.$store.dispatch('contact/getGrouplist');
- this.$store.dispatch('conversation/getUnReadCount');
- this.$store.commit('user/SET_IS_SYNCING', false);
- if (offlineMsg != null) {
- uni.$u.throttle(() => this.notifyGoToChat(offlineHandleNewMsg), 500);
- }
- uni.hideLoading();
- };
- const syncFailedHandler = () => {
- uni.hideLoading();
- //uni.$u.toast('同步消息失败');
- this.$store.dispatch('conversation/getConversationList');
- this.$store.dispatch('conversation/getUnReadCount');
- this.$store.commit('user/SET_IS_SYNCING', false);
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerStart, syncStartHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerFinish, syncFinishHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerFailed, syncFailedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerProgress, syncProgressHandler);
- // self
- const selfInfoUpdateHandler = ({
- data
- }) => {
- this.$store.commit('user/SET_SELF_INFO', {
- ...this.storeSelfInfo,
- ...data
- });
- this.updateMessageNicknameAndFaceUrl({
- sendID: data.userID,
- senderNickname: data.nickname,
- senderFaceUrl: data.faceURL
- });
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnSelfInfoUpdated, selfInfoUpdateHandler);
- // message
- const newMessagesHandler = ({
- data
- }) => {
- console.log("-----qxj newMessagesHandler:" + JSON.stringify(data));
- if (offlineMsg != null) {
- offlineHandleNewMsg = data[0];
- }
- if (this.storeIsSyncing) {
- return;
- }
- data.forEach(this.handleNewMessage);
- };
- const offlineMessageHandler = ({
- data
- }) => {
- console.log("-----qxj offlineMessageHandler:" + JSON.stringify(data));
- };
- const offlineMessagesHandler = ({
- data
- }) => {
- console.log("------offlineMessagesHandler:" + JSON.stringify(data));
- if (this.storeIsSyncing) {
- return;
- }
- data.forEach(this.handleOfflineMessages);
- };
- const c2cReadReceiptHandler = ({
- data: receiptList
- }) => {
- if (receiptList[0].userID !== this.storeCurrentConversation.userID) {
- return;
- }
- receiptList.forEach((item) => {
- item.msgIDList.forEach((msgID) => {
- this.updateOneMessage({
- message: {
- clientMsgID: msgID
- },
- type: UpdateMessageTypes.KeyWords,
- keyWords: {
- key: 'isRead',
- value: true
- }
- });
- });
- });
- };
- const groupReadReceiptHandler = ({
- data
- }) => {
- if (data.conversationID !== this.storeCurrentConversation.conversationID) {
- return;
- }
- data.groupMessageReadInfo.map((receipt) => {
- const oldMessage = this.storeHistoryMessageList.find((msg) => msg.clientMsgID ===
- receipt.clientMsgID);
- if (oldMessage) {
- uni.$emit(PageEvents.GroupMessageReceipt, receipt);
- const newMessage = {
- ...oldMessage,
- isRead: true,
- attachedInfoElem: {
- ...oldMessage.attachedInfoElem,
- groupHasReadInfo: {
- hasReadCount: receipt.hasReadCount,
- unreadCount: receipt.unreadCount
- }
- }
- };
- console.log(newMessage);
- this.updateOneMessage({
- message: newMessage
- });
- }
- });
- };
- const newRecvMessageRevokedHandler = ({
- data: revokedMessage
- }) => {
- if (!this.storeCurrentConversation.conversationID) {
- return;
- }
- this.updateOneMessage({
- message: {
- clientMsgID: revokedMessage.clientMsgID
- },
- type: UpdateMessageTypes.KeyWords,
- keyWords: [{
- key: 'contentType',
- value: MessageType.RevokeMessage
- },
- {
- key: 'notificationElem',
- value: {
- detail: JSON.stringify(revokedMessage)
- }
- }
- ]
- });
- this.updateQuoteMessageRevoke({
- clientMsgID: revokedMessage.clientMsgID
- });
- };
- const inputStatusChanged = ({
- data
- }) => {
- if (data.userID === this.storeCurrentConversation.userID && data.conversationID === this
- .storeCurrentConversation.conversationID) {
- if (data.platformIDs.length > 0) {
- uni.$emit(PageEvents.TypingUpdate);
- }
- }
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnRecvOfflineNewMessage, offlineMessageHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnRecvOfflineNewMessages, offlineMessagesHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnRecvNewMessages, newMessagesHandler);
- IMSDK.subscribe("OnInputStatusChanged", inputStatusChanged);
- IMSDK.subscribe(IMSDK.IMEvents.OnRecvC2CReadReceipt, c2cReadReceiptHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnRecvGroupReadReceipt, groupReadReceiptHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnNewRecvMessageRevoked, newRecvMessageRevokedHandler);
- // friend
- const friendInfoChangeHandler = ({
- data
- }) => {
- uni.$emit(IMSDK.IMEvents.OnFriendInfoChanged, {
- data
- });
- if (data.userID === this.storeCurrentConversation?.userID) {
- this.updateMessageNicknameAndFaceUrl({
- sendID: data.userID,
- senderNickname: data.remark || data.nickname,
- senderFaceUrl: data.faceURL
- });
- this.$store.commit('conversation/SET_CURRENT_CONVERSATION', {
- ...this.storeCurrentConversation,
- showName: data.remark || data.nickname
- });
- }
- console.log(this.storeConversationList);
- this.updateFriendInfo({
- friendInfo: data
- });
- };
- const friendAddedHandler = ({
- data
- }) => {
- this.pushNewFriend(data);
- };
- const friendDeletedHander = ({
- data
- }) => {
- this.updateFriendInfo({
- friendInfo: data,
- isRemove: true
- });
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnFriendInfoChanged, friendInfoChangeHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnFriendAdded, friendAddedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnFriendDeleted, friendDeletedHander);
- // blacklist
- const blackAddedHandler = ({
- data
- }) => {
- this.pushNewBlack(data);
- };
- const blackDeletedHandler = ({
- data
- }) => {
- this.updateBlackInfo({
- blackInfo: data,
- isRemove: true
- });
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnBlackAdded, blackAddedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnBlackDeleted, blackDeletedHandler);
- // group
- const joinedGroupAddedHandler = ({
- data
- }) => {
- uni.$emit(IMSDK.IMEvents.OnJoinedGroupAdded, {
- data
- });
- this.pushNewGroup(data);
- };
- const joinedGroupDeletedHandler = ({
- data
- }) => {
- uni.$emit(IMSDK.IMEvents.OnJoinedGroupDeleted, {
- data
- });
- this.updateGroupInfo({
- groupInfo: data,
- isRemove: true
- });
- };
- const groupInfoChangedHandler = ({
- data
- }) => {
- this.updateGroupInfo({
- groupInfo: data
- });
- };
- const groupMemberInfoChangedHandler = ({
- data
- }) => {
- uni.$emit(IMSDK.IMEvents.OnGroupMemberInfoChanged, {
- data
- });
- if (data.groupID === this.storeCurrentConversation?.groupID) {
- this.updateMessageNicknameAndFaceUrl({
- sendID: data.userID,
- senderNickname: data.nickname,
- senderFaceUrl: data.faceURL
- });
- this.updateCurrentMemberInGroup(data);
- }
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnJoinedGroupAdded, joinedGroupAddedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnJoinedGroupDeleted, joinedGroupDeletedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnGroupInfoChanged, groupInfoChangedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnGroupMemberInfoChanged, groupMemberInfoChangedHandler);
- // application
- const friendApplicationNumHandler = ({
- data
- }) => {
- const isRecv = data.toUserID === this.storeCurrentUserID;
- if (isRecv) {
- this.pushNewRecvFriendApplition(data);
- } else {
- this.pushNewSentFriendApplition(data);
- }
- };
- const friendApplicationAccessHandler = ({
- data
- }) => {
- const isRecv = data.toUserID === this.storeCurrentUserID;
- if (isRecv) {
- this.updateRecvFriendApplition({
- application: data
- });
- } else {
- this.updateSentFriendApplition({
- application: data
- });
- }
- };
- const groupApplicationNumHandler = ({
- data
- }) => {
- const isRecv = data.userID !== this.storeCurrentUserID;
- if (isRecv) {
- this.pushNewRecvGroupApplition(data);
- } else {
- this.pushNewSentGroupApplition(data);
- }
- };
- const groupApplicationAccessHandler = ({
- data
- }) => {
- const isRecv = data.userID !== this.storeCurrentUserID;
- if (isRecv) {
- this.updateRecvGroupApplition({
- application: data
- });
- } else {
- this.updateSentGroupApplition({
- application: data
- });
- }
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnFriendApplicationAdded, friendApplicationNumHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnFriendApplicationAccepted, friendApplicationAccessHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnFriendApplicationRejected, friendApplicationAccessHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnGroupApplicationAdded, groupApplicationNumHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnGroupApplicationAccepted, groupApplicationAccessHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnGroupApplicationRejected, groupApplicationAccessHandler);
- // conversation
- const totalUnreadCountChangedHandler = ({
- data
- }) => {
- if (this.storeIsSyncing) {
- return;
- }
- this.$store.commit('conversation/SET_UNREAD_COUNT', data);
- };
- const newConversationHandler = ({
- data
- }) => {
- console.log("qxj newConversationHandler");
- if (this.storeIsSyncing) {
- return;
- }
- const result = [...data, ...this.storeConversationList];
- this.$store.commit('conversation/SET_CONVERSATION_LIST', conversationSort(result));
- };
- const conversationChangedHandler = ({
- data
- }) => {
- if (this.storeIsSyncing) {
- return;
- }
- let filterArr = [];
- console.log("qxj conversationChangedHandler:::", data);
- const chids = data.map((ch) => ch.conversationID);
- filterArr = this.storeConversationList.filter((tc) => !chids.includes(tc.conversationID));
- const idx = data.findIndex((c) => c.conversationID === this.storeCurrentConversation
- .conversationID);
- if (idx !== -1) this.$store.commit('conversation/SET_CURRENT_CONVERSATION', data[idx]);
- const result = [...data, ...filterArr];
- this.$store.commit('conversation/SET_CONVERSATION_LIST', conversationSort(result));
- };
- IMSDK.subscribe(IMSDK.IMEvents.OnTotalUnreadMessageCountChanged, totalUnreadCountChangedHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnNewConversation, newConversationHandler);
- IMSDK.subscribe(IMSDK.IMEvents.OnConversationChanged, conversationChangedHandler);
- const insertInCurrentConversation = (newServerMsg) => {
- return newServerMsg.sendID === this.$store.getters.storeCurrentConversation.userID || newServerMsg
- .recvID === this.$store.getters.storeCurrentConversation.userID;
- };
- const onNativeCallEndHandler = async ({
- invitation,
- duration,
- status
- }) => {
- uni.$emit(PageEvents.NativeCallEnd);
- if (!status || invitation.groupID) {
- return;
- }
- const type = invitation.mediaType === 'video' ? CustomType.VideoCall : CustomType.VoiceCall;
- const customData = {
- customType: CustomType.Call,
- data: {
- type,
- duration: secFormat(duration),
- status
- }
- };
- const nativeCallList = uni.getStorageSync(
- `${this.$store.getters.storeCurrentUserID}_nativecall`) || [];
- const isSelf = invitation.inviterUserID === this.$store.getters.storeCurrentUserID;
- const data = {
- ...invitation,
- duration,
- isSelf,
- type,
- time: new Date().getTime()
- };
- uni.setStorage({
- key: `${this.$store.getters.storeCurrentUserID}_nativecall`,
- data: [...nativeCallList, data]
- });
- const message = await IMSDK.asyncApi(IMMethods.CreateCustomMessage, IMSDK.uuid(), {
- data: JSON.stringify(customData),
- extension: '',
- description: 'RTC'
- });
- const recvID = invitation.inviteeUserIDList[0];
- IMSDK.asyncApi(IMSDK.IMMethods.InsertSingleMessageToLocalStorage, IMSDK.uuid(), {
- message,
- recvID,
- sendID: invitation.inviterUserID
- }).then(({
- data
- }) => {
- if (insertInCurrentConversation(data)) {
- this.$store.dispatch('message/pushNewMessage', data);
- setTimeout(() => uni.$emit(PageEvents.ScrollToBottom, true));
- }
- }).catch((err) => {
- console.log(err);
- });
- };
- const onNativeInviteHandler = async (data) => {
- // uni.$u.toast("onNativeInviteHandler")
- uni.$u.route('/pages_im/pages/common/contactChoose/index', {
- type: ContactChooseTypes.InviteMeeting,
- forwardMessage: encodeURIComponent(JSON.stringify(data.data))
- });
- };
- IMSDK.subscribe('onNativeCallEnd', onNativeCallEndHandler);
- IMSDK.subscribe('Native_InviteUser', onNativeInviteHandler);
- },
- initOpenIm() {
- innerAudioContext = uni.createInnerAudioContext();
- innerAudioContext.autoplay = false;
- innerAudioContext.src = newMessage;
- // #ifdef APP-PLUS
- //Igexin.turnOnPush();
- //#endif
- this.setGlobalIMlistener();
- this.tryLogin();
- },
- openImLogin() {
- let that = this;
- var uid = "";
- var nickName = "";
- var avatar = "";
- if (this.$companyUserIsLogin()) {
- var user = JSON.parse(uni.getStorageSync('companyUser'));
- uid = 'C' + user.userId;
- nickName = user.imNickName || user.nickName || user.nickname;
- avatar = user.avatar;
- } else {
- var user = JSON.parse(uni.getStorageSync('userInfo'));
- uid = 'U' + user.userId;
- nickName = user.nickName || user.nickname;
- avatar = user.avatar;
- }
- if (this.$isEmpty(avatar)) {
- avatar =
- "https://fbylive.obs.cn-southwest-2.myhuaweicloud.com/app/appimgs/4e7c1c2de4b54ec4aaf1047394592a42.png";
- }
- let IMToken = uni.getStorageSync('IMToken');
- let IMUserID = uid;
- let reqData = {
- userID: uid,
- nickName: nickName,
- avatar: avatar
- };
- openImLoginApi(reqData, IMToken, IMUserID, function(token) {
- setTimeout(() => {
- that.tryLogin();
- }, 100);
- },
- function() {
- //uni.$u.toast('IM登录失败');
- }
- );
- },
- tryLogin() {
- const initStore = () => {
- this.$store.dispatch('user/initCache');
- this.$store.dispatch('user/getSelfInfo');
- this.$store.dispatch('conversation/getConversationList');
- this.$store.dispatch('conversation/getUnReadCount');
- // this.$store.dispatch("contact/getFriendList");
- // this.$store.dispatch("contact/getGrouplist");
- this.$store.dispatch('contact/getBlacklist');
- this.$store.dispatch('contact/getRecvFriendApplications');
- this.$store.dispatch('contact/getSentFriendApplications');
- this.$store.dispatch('contact/getRecvGroupApplications');
- this.$store.dispatch('contact/getSentGroupApplications');
- // #ifdef APP-PLUS
- //Igexin.bindAlias(IMUserID);
- plus.navigator.closeSplashscreen();
- // #endif
- };
- let IMToken = uni.getStorageSync('IMToken');
- let IMUserID = uni.getStorageSync('IMUserID');
- // #ifdef APP-PLUS
- getDbDir().then(async (path) => {
- let platformID = uni.$u.os() === 'ios' ? 1 : 2;
- const flag = await IMSDK.asyncApi(IMMethods.InitSDK, IMSDK.uuid(), {
- systemType: 'uni-app',
- platformID: platformID,
- apiAddr: config.getApiUrl(),
- wsAddr: config.getWsUrl(),
- dataDir: path, // 数据存储路径
- logLevel: 1,
- logFilePath: path,
- isLogStandardOutput: false // 是否输出到控制台
- });
- if (!flag) {
- // #ifdef APP-PLUS
- plus.navigator.closeSplashscreen();
- // #endif
- uni.$u.toast('初始化IMSDK失败!');
- return;
- }
- //1 未登录 2 登录中 3 已登录
- const loginStatus = await IMSDK.asyncApi(IMSDK.IMMethods.GetLoginStatus, IMSDK.uuid());
- if (loginStatus === 3) {
- initStore();
- return;
- }
- callingModule?.initModule();
- if (IMToken && IMUserID) {
- await IMSDK.asyncApi(IMSDK.IMMethods.Login, IMSDK.uuid(), {
- userID: IMUserID,
- token: IMToken,
- }).then(initStore).catch((err) => {
- console.log('qxj initStore err:' + JSON.stringify(err));
- uni.$u.toast('初始化IMSDK异常:' + JSON.stringify(err));
- uni.removeStorage({
- key: 'IMToken'
- });
- // #ifdef APP-PLUS
- plus.navigator.closeSplashscreen();
- // #endif
- });
- } else {
- if (this.$isLogin()) {
- this.openImLogin();
- }
- // #ifdef APP-PLUS
- plus.navigator.closeSplashscreen();
- // #endif
- }
- }).catch((err) => {
- console.log('get dir failed');
- console.log(err);
- // #ifdef APP-PLUS
- plus.navigator.closeSplashscreen();
- // #endif
- });
- // #endif
- // #ifdef H5
- if (IMToken && IMUserID) {
- IMSDK.asyncApi(IMSDK.IMMethods.Login, IMSDK.uuid(), {
- userID: IMUserID,
- token: IMToken,
- platformID: 5,
- logLevel: 3,
- apiAddr: config.getApiUrl(),
- wsAddr: config.getWsUrl(),
- }).then(initStore).catch((err) => {
- uni.removeStorage({
- key: 'IMToken'
- });
- });
- } else {
- if (this.$isLogin()) {
- this.openImLogin();
- }
- }
- // #endif
- },
- async newMessageNotify(newServerMsg) {
- if (this.storeIsSyncing) {
- return;
- }
- console.log("qxj newMessageNotify1");
- const disableNotify = uni.getStorageSync(`${this.storeCurrentUserID}_DisableNotify`);
- if (disableNotify || this.storeSelfInfo.globalRecvMsgOpt !== MessageReceiveOptType.Nomal) {
- return;
- }
- console.log("qxj newMessageNotify2");
- let cveItem = [...this.storeConversationList, ...cacheConversationList].find((conversation) => {
- if (newServerMsg.sessionType === SessionType.WorkingGroup) {
- return newServerMsg.groupID === conversation.groupID;
- }
- return newServerMsg.sendID === conversation.userID;
- });
- console.log("qxj newMessageNotify3");
- if (!cveItem) {
- try {
- const {
- data
- } = await IMSDK.asyncApi(IMSDK.IMMethods.GetOneConversation, IMSDK.uuid(), {
- sourceID: newServerMsg.groupID || newServerMsg.sendID,
- sessionType: newServerMsg.sessionType
- });
- cveItem = data;
- cacheConversationList = [...cacheConversationList, data];
- } catch (e) {
- return;
- }
- }
- console.log("qxj newMessageNotify4");
- if (cveItem.recvMsgOpt !== MessageReceiveOptType.Nomal) {
- return;
- }
- console.log("qxj newMessageNotify5");
- const notificationFun = () => {
- const isSelf = newServerMsg.sendID === this.$store.getters.storeCurrentUserID;
- if (isSelf) return;
- const pages = getCurrentPages();
- const url = pages[pages.length - 1];
- console.log("qxj route:" + url.route);
- if (url && (url.route == "pages_im/pages/conversation/conversationList/index" ||
- url.route == "pages_im/pages/conversation/chating/index")) {
- return;
- }
- // uni.createPushMessage({
- // content: `${newServerMsg.senderNickname}: ${parseMessageByType(newServerMsg)}`,
- // payload: {
- // sessionType: newServerMsg.sessionType,
- // sourceID: newServerMsg.groupID || newServerMsg.sendID,
- // }
- // });
- const isSingle = newServerMsg.groupID ? false : true;
- console.log(this.storeGroupList, newServerMsg);
- const group = this.storeGroupList.filter((group) => group.groupID === newServerMsg.groupID);
- const title = isSingle ? newServerMsg.senderNickname : group[0].groupName;
- const desc = parseMessageByType(newServerMsg);
- console.log('notification', title, desc);
- // notificationIntance = new NotificationUtil();
- // let tickerTips="通知提示";
- // let notifyId=10001;
- // let config={ title, desc,tickerTips,notifyId };
- // notificationIntance.createNotification(config);
- // setTimeout(()=>{
- // notificationIntance.clearNotification(10001);
- // },10000);
- // notification.showNotice(0, title, desc, () => {
- // prepareConversationState(cveItem);
- // });
- };
- //notificationFun();
- const platform = uni.getSystemInfoSync().platform;
- if (platform == 'ios') {
- if (this.storeSelfInfo.allowVibration === 1) {
- plus.device.vibrate();
- }
- if (this.storeSelfInfo.allowBeep === 1) {
- innerAudioContext.play();
- // plus.device.beep();
- }
- } else if (platform == 'android') {
- if (this.storeSelfInfo.allowVibration === 1) {
- plus.device.vibrate(500);
- }
- if (this.storeSelfInfo.allowBeep === 1) {
- let main = plus.android.runtimeMainActivity();
- let RingtoneManager = plus.android.importClass('android.media.RingtoneManager');
- let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
- let MediaPlayer = plus.android.importClass('android.media.MediaPlayer');
- let player = MediaPlayer.create(main, uri);
- player.setLooping(false);
- player.prepare();
- player.start();
- }
- }
- },
- async notifyGoToChat(newServerMsg) {
- if (this.storeIsSyncing) {
- return;
- }
- offlineHandleNewMsg = null;
- offlineMsg = null;
- const disableNotify = uni.getStorageSync(`${this.storeCurrentUserID}_DisableNotify`);
- if (disableNotify || this.storeSelfInfo.globalRecvMsgOpt !== MessageReceiveOptType.Nomal) {
- return;
- }
- let cveItem = [...this.storeConversationList, ...cacheConversationList].find((conversation) => {
- if (newServerMsg.sessionType === SessionType.WorkingGroup) {
- return newServerMsg.groupID === conversation.groupID;
- }
- return newServerMsg.sendID === conversation.userID;
- });
- if (!cveItem) {
- try {
- const {
- data
- } = await IMSDK.asyncApi(IMSDK.IMMethods.GetOneConversation, IMSDK.uuid(), {
- sourceID: newServerMsg.groupID || newServerMsg.sendID,
- sessionType: newServerMsg.sessionType
- });
- cveItem = data;
- cacheConversationList = [...cacheConversationList, data];
- } catch (e) {
- return;
- }
- }
- if (cveItem.recvMsgOpt !== MessageReceiveOptType.Nomal) {
- return;
- }
- const isSelf = newServerMsg.sendID === this.$store.getters.storeCurrentUserID;
- if (isSelf) return;
- const pages = getCurrentPages();
- const url = pages[pages.length - 1];
- if (url && (url.route == "pages_im/pages/conversation/chating/index")) {
- return;
- }
- this.handlerConversation(cveItem);
- prepareConversationState(cveItem);
- },
- handlerConversation(source) {
- let userId = source.userID;
- let isDoctor = false;
- if (userId != undefined && (userId != "" || userId.length > 0)) {
- if (userId.indexOf('D') !== -1) {
- isDoctor = true;
- }
- }
- if (this.$companyUserIsLogin() || !isDoctor) {
- this.$store.commit("timStore/setImType", 1);
- } else {
- let ex = source.ex;
- if (source.latestMsg != null && source.latestMsg != '') {
- let latestMsg = JSON.parse(source.latestMsg);
- if (!!latestMsg.ex && latestMsg.ex != '') {
- ex = latestMsg.ex;
- }
- }
- if (ex != null || ex != '') {
- try {
- var json = JSON.parse(ex);
- this.$store.commit("timStore/setImType", json.imType);
- this.$store.commit("timStore/setOrderType", json.orderType);
- this.$store.commit("timStore/setOrderId", json.orderId);
- this.$store.commit("timStore/setFollowId", json.followId);
- this.$store.commit("timStore/setType", json.type);
- } catch (e) {
- }
- }
- }
- this.$store.commit("timStore/setConversationID", source.conversationID);
- },
- handleNewMessage(newServerMsg) {
- console.log("---qxj newServerMsg", newServerMsg);
- if (this.inCurrentConversation(newServerMsg)) {
- console.log("---qxj inCurrentConversation");
- const isSingleMessage = newServerMsg.sessionType === SessionType.Single;
- if (isSingleMessage) {
- uni.$u.throttle(() => uni.$emit(PageEvents.OnlineStateCheck), 2000);
- if (newServerMsg.ex != null && newServerMsg.ex != '') {
- var json = JSON.parse(newServerMsg.ex);
- this.$store.commit("timStore/setType", json.type);
- this.$store.commit("timStore/setImType", json.imType);
- this.$store.commit("timStore/setOrderId", json.orderId);
- this.$store.commit("timStore/setOrderType", json.orderType);
- this.$store.commit("timStore/setFollowId", json.followId);
- if (json.type === "finishInquiry") {
- this.$store.commit("timStore/setImType", 0);
- uni.navigateTo({
- url: "/pages_order/pingOrder?orderId=" + json.orderId
- })
- } else if (json.type === "startInquiry") {
- } else if (json.type === "inquiry") {
- } else if (json.type === "startFollow") {
- } else if (json.type === "follow") {
- } else if (json.type === "finishFollow") {
- } else if (json.type === "startDrugReport") {
- } else if (json.type === "finishDrugReport") {
- } else if (json.type === "drugReport") {
- }
- }
- }
- if (newServerMsg.contentType === MessageType.TypingMessage) {
- if (isSingleMessage) {
- uni.$emit(PageEvents.TypingUpdate);
- }
- } else {
- if (newServerMsg.contentType === MessageType.RevokeMessage) {
- } else {
- newServerMsg.isAppend = true;
- this.pushNewMessage(newServerMsg);
- setTimeout(() => uni.$emit(PageEvents.ScrollToBottom, true));
- }
- uni.$u.debounce(this.markConversationAsRead, 2000);
- }
- } else {
- if (newServerMsg.contentType !== MessageType.TypingMessage) {
- uni.$u.throttle(() => this.newMessageNotify(newServerMsg), 1000);
- setTimeout(() => {
- this.$store.dispatch('conversation/getUnReadCount');
- }, 500);
- }
- }
- },
- handleOfflineMessages(newServerMsg) { //后台运行
- const isSingle = newServerMsg.groupID ? false : true;
- console.log(this.storeGroupList, newServerMsg);
- const group = this.storeGroupList.filter((group) => group.groupID === newServerMsg.groupID);
- const title = isSingle ? newServerMsg.senderNickname : group[0].groupName;
- const desc = parseMessageByType(newServerMsg);
- // if(notification){
- // notification.showNotice(0, title, desc, () => {
- // console.log('qxj showNotice:', title);
- // //prepareConversationState(cveItem);
- // });
- // }
- // const options = {
- // title: title,
- // content: desc,
- // payload: newServerMsg, // 自定义参数,点击通知时传递给应用
- // sound: 'default', // 通知声音
- // cover: false, // 是否覆盖之前的通知
- // //when: new Date(),
- // icon:"",
- // extras: {
- // android: {
- // importance: "high", // 高优先级
- // channelId: "sticky_channel", // 必须配置通知渠道
- // smallIcon: "transparent",
- // showWhen: false,
- // }
- // }
- // };
- // plus.push.createMessage(options.content, options.payload, options);
- // let when=new Date();
- // uni.createPushMessage({
- // title:title,
- // content:desc,
- // payload: newServerMsg,
- // cover: false, // 是否覆盖之前的通知
- // when: new Date()
- // });
- },
- inCurrentConversation(newServerMsg) {
- switch (newServerMsg.sessionType) {
- case SessionType.Single:
- return (
- newServerMsg.sendID === this.storeCurrentConversation.userID ||
- (newServerMsg.sendID === this.storeCurrentUserID && newServerMsg.recvID === this
- .storeCurrentConversation.userID)
- );
- case SessionType.WorkingGroup:
- return newServerMsg.groupID === this.storeCurrentConversation.groupID;
- case SessionType.Notification:
- return newServerMsg.sendID === this.storeCurrentConversation.userID;
- default:
- return false;
- }
- },
- markConversationAsRead() {
- IMSDK.asyncApi(IMSDK.IMMethods.MarkConversationMessageAsRead, IMSDK.uuid(), this.storeCurrentConversation
- .conversationID);
- },
- removeImData() {
- uni.removeStorage({
- key: 'IMToken'
- });
- uni.removeStorage({
- key: 'IMUserID'
- });
- },
- async cidBindAlias(alias) {
- let registrationID = uni.getStorageSync("registrationID");
- let params = [{
- "cid": registrationID,
- "alias": alias
- }];
- console.log("qxj cidBindAlias params:" + JSON.stringify(params));
- await uniPush.cidBindAlias(params);
- },
- runTimer() {
- let that = this;
- let dateNowDay = this.$dateFormatStr('YYYY-mm-dd', new Date());
- let healthButler = uni.getStorageSync('healthButler');
- let userInfo = uni.getStorageSync('userInfo');
- console.log('------qxj dateStr:' + dateNowDay + ' healthButler:' + healthButler);
- let dayNum = 0;
- if (userInfo != null && userInfo.isAddQw) {
- //已加过企微不在弹窗
- return;
- }
- if (!!healthButler) {
- healthButler = JSON.parse(healthButler);
- dayNum = healthButler.dayNum;
- if (healthButler.day == dateNowDay) {
- //今天已经弹窗过 防止再弹窗
- return;
- }
- }
- if (dayNum == 0) {
- //第一天下载App
- if (this.$qconfig.healthTimer == null) {
- this.$qconfig.healthTimer = setInterval(() => {
- if (this.$qconfig.healthSeconds == healthSeconds) {
- this.$qconfig.healthSeconds = 0;
- healthButlerPop(function(data) {
- if (data == 1) {
- that.bdAdvFeedback();
- clearInterval(that.$qconfig.healthTimer);
- } else {
- that.resetTimer();
- that.$showLoginPage();
- }
- });
- }
- this.$qconfig.healthSeconds++;
- //console.log("healthTimer tSeconds:"+this.$qconfig.healthSeconds);
- }, 1000);
- }
- } else {
- //第二天,第三天,,
- healthButlerPop(function(data) {
- if (data == 1) {
- clearInterval(that.$qconfig.healthTimer);
- } else {
- that.$showLoginPage();
- }
- });
- }
- },
- resetTimer() {
- clearInterval(this.$qconfig.healthTimer);
- this.$qconfig.healthTimer = null; //重置定时器
- this.$qconfig.healthSeconds = healthSeconds;
- },
- getUserInfo(healthButler) {
- getUserInfo().then((res) => {
- if (res.code == 200) {
- if (res.user != null) {
- uni.setStorageSync('userInfo', JSON.stringify(res.user));
- let userInfo = res.user;
- healthButler.isAddQw = userInfo.isAddQw;
- uni.setStorageSync('healthButler', JSON.stringify(healthButler));
- }
- }
- },
- (rej) => {}
- );
- },
- jumpToNotificationSettings() {
- uni.request({
- url: 'content://settings/action/notification_settings',
- success: function(res) {
- console.log('跳转成功:', res);
- },
- fail: function(err) {
- console.log('跳转失败:', err);
- }
- });
- },
- bdAdvFeedback() {
- // #ifdef APP-PLUS
- if (plus.runtime.isAgreePrivacy()) {
- if (plus.runtime.channel == 'baidu') {
- let bdCmdType = uni.getStorageSync('bdCmdType');
- if (this.$isEmpty(bdCmdType)) {
- this.$registerIdCode('goToQw', 4, 0);
- }
- }
- }
- // #endif
- },
- async checkPush1() {
- let result = await premissionCheck("PUSH");
- if (result == 1) {
- }
- // uPushPlugin.setCustomPushChannel({
- // soundName: "",
- // channelId: "133898",
- // channelDesc:"看课提醒",
- // enableLights:true,
- // enableVibration:true,
- // importance:4,
- // lockscreenVisibility:1
- // });
- // uPushPlugin.getAllChannels((p) => {
- // console.log("qxj push channels :" + JSON.stringify(p));//返回数组
- // });
- // const manager = uni.getChannelManager()
- // manager.setPushChannel({
- // "channelId":"Push",
- // "channelDesc":"消息推送",
- // "enableLights":true,
- // "importance":4,
- // "lockscreenVisibility":1
- // //soundName: "pushsound" // 已经把声音文件存储到/res/raw/pushsound.mp3
- // });
- },
- async checkPush() {
- //检测是否开启推送通知
- const notificationAuthorized = uni.getAppAuthorizeSetting().notificationAuthorized;
- if (notificationAuthorized == 'denied') {
- uni.showModal({
- title: '提示',
- content: '是否前往打开通知权限',
- success: (res) => {
- if (res.confirm) {
- let status = this.checkPermission();
- if (status !== 1) {
- console.log('未开启权限');
- }
- } else if (res.cancel) {
- console.log('用户点击取消');
- }
- }
- });
- }
- },
- async checkPermission() {
- let status = permision1.isIOS ? await permision1.requestIOS('push') :
- await permision1.requestAndroid('android.permission.REQUEST_NOTIFICATION_POLICY');
- if (status === null || status === 1) {
- status = 1;
- } else if (status === 2) {
- uni.showModal({
- content: '系统通知已关闭',
- confirmText: '确定',
- showCancel: false,
- success: function(res) {}
- });
- } else if (status.code) {
- uni.showModal({
- content: status.message
- });
- } else {
- uni.showModal({
- content: '需要通知权限',
- confirmText: '设置',
- success: function(res) {
- if (res.confirm) {
- permision1.gotoAppSetting();
- }
- }
- });
- }
- return status;
- },
- geth5Path() {
- this.handlePushMessage()
- getRealLinkDomainName().then((res) => {
- if (res.code == 200) {
- uni.setStorageSync('h5Path', res.data);
- }
- });
- },
- handlePushMessage(res) {
- const that = this;
- if (res.type == 'click') {
- // 如果需要跳转app内指定页面,则自己实现下方的跳转代码。
- if (this.$isLogin()) {
- const pages = getCurrentPages();
- const url = pages[pages.length - 1];
- const isOnLaunch = uni.getStorageSync('onLaunch');
- // 判断前一个页面路径是一样
- const flag = pages && url.route && res.data.payload.url.indexOf(url.route);
- // console.log("点击===========",url.route,flag)
- if (isOnLaunch && isOnLaunch == 1) {
- uni.hideLoading({
- title: '处理中..'
- });
- setTimeout(() => {
- uni.hideLoading();
- if (flag == -1) {
- uni.navigateTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- } else {
- uni.redirectTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- }
- }, 1000);
- } else {
- uni.hideLoading();
- if (flag == -1) {
- uni.navigateTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- } else {
- uni.redirectTo({
- url: res.data.payload.url,
- success: function() {
- uni.removeStorageSync('openUrl');
- that.setReadAll(res.data.payload.url);
- }
- });
- }
- }
- }
- } else if (res.type == 'receive') {
- //监听在线推送消息,若云函数设置了 "force_notification":true,则不会触发此 receive。
- }
- },
- // 系统通知全部已读
- setReadAll(url) {
- if (url && url.indexOf('/pages/courseAnswer/index') == -1) {
- getPushLogRead([]).then((res) => {
- if (res.code == 200) {
- this.$updateMsgDot();
- }
- });
- }
- },
- // 获取剪贴板内容跳转到看课
- getClipboardData() {
- // #ifdef APP-PLUS
- const course = {};
- coursePopup(course, () => {
- // uni.getClipboardData({
- // success: function (res) {
- // console.log("res.data===",res);
- // let Context = plus.android.importClass("android.content.Context");
- // let main = plus.android.runtimeMainActivity();
- // let clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
- // plus.android.invoke(clip,"setText","");
- // }
- // });
- });
- // #endif
- },
- getRuntimePlatform() {
- const systemInfo = uni.getSystemInfoSync();
- const compilePlatform = process.env.UNI_PLATFORM;
- //1:iOS,2:Android,3:Windows,4:OSX,5:WEB,6:小程序,7:linux,8:AndroidPad,9:IPad,10:Admin
- let platformType = 5;
- // H5 环境
- if (compilePlatform === 'h5') platformType = 5;
- // 小程序环境
- if (compilePlatform.startsWith('mp-')) {
- const mpType = compilePlatform.split('-')[1]; // 如 weixin/alipay
- platformType = 6;
- // return `小程序(${mpType})- ${systemInfo.platform}`;
- }
- // App 环境
- if (compilePlatform === 'app-plus') {
- if (systemInfo.platform.toLowerCase() === 'android') {
- platformType = 2;
- }
- if (systemInfo.platform.toLowerCase() === 'ios') {
- platformType = 1;
- }
- }
- return platformType;
- },
- /* 检查更新 在线更新 */
- checkUpdateApp() {
- //uni wgt包版本检测更新
- checkUpdate();
- let that = this;
- plus.runtime.getProperty(plus.runtime.appid, function(widgetinfo) {
- if (widgetinfo.name == qconfig.appName) {
- let platform = uni.getSystemInfoSync().platform;
- let isAndroid = platform == 'android';
- let type = isAndroid ? 1 : 2;
- getAppVersion(type).then((srcData) => {
- if (srcData.code == 200) {
- let data = srcData.data;
- let version = widgetinfo.versionCode, //用户当前app版本
- appVersion = data.versionCode, //升级包版本
- appName = widgetinfo.name, //app名称
- isForce = data.isForce, //是否强制热更新
- updateConfig = JSON.parse(data.updateConfig),
- appurl = data.url, //升级包地址
- intro = data.note; //升级包提示
- //如果用户版本号小于升级包版本号,先升级
- let afterVer = false;
- if (plus.runtime.channel == 'baidu') {
- afterVer = that.$qconfig.isAppStore ? updateConfig.baidu : false;
- } else if (plus.runtime.channel == 'huawei') {
- afterVer = that.$qconfig.isAppStore ? updateConfig.huawei : false;
- } else if (plus.runtime.channel == 'xiaomi') {
- afterVer = that.$qconfig.isAppStore ? updateConfig.xiaomi : false;
- } else if (plus.runtime.channel == 'yyb') {
- afterVer = that.$qconfig.isAppStore ? updateConfig.yyb : false;
- } else {
- afterVer = that.$qconfig.isAppStore ? isForce : true;
- }
- if (data && version < appVersion && afterVer) {
- uni.showModal({
- title: '更新提示',
- confirmText: '立即升级',
- content: intro,
- cancelText: '确定',
- confirmText: '取消',
- success: (res) => {
- if (res.cancel) {
- openDownload(srcData.data);
- } else if (res.confirm) {
- if (isForce == 1) {
- uni.showToast({
- title: '请先升级APP版本',
- icon: 'none',
- duration: 2000
- });
- //退出app
- setTimeout(function() {
- plus.runtime.quit();
- }, 2000);
- }
- }
- },
- fail: () => {
- uni.hideLoading();
- }
- });
- }
- }
- },
- (rej) => {}
- )
- .catch(() => {
- //联网失败, 结束加载
- this.mescroll.endErr();
- });
- }
- });
- }
- },
- watch: {
- storeCurrentUserID(newVal) {
- if (newVal) {
- cacheConversationList = [];
- }
- },
- contactBadgeRely: {
- handler(newValue) {
- const {
- recvFriendApplications,
- recvGroupApplications,
- userKey
- } = newValue;
- if (!userKey) return;
- const accessedFriendApplications = uni.getStorageSync(`${userKey}_accessedFriendApplications`) || [];
- let unHandleFriendApplicationNum = recvFriendApplications.filter(
- (application) => application.handleResult === 0 && !accessedFriendApplications.includes(
- `${application.fromUserID}_${application.createTime}`)
- ).length;
- const accessedGroupApplications = uni.getStorageSync(`${userKey}_accessedGroupApplications`) || [];
- let unHandleGroupApplicationNum = recvGroupApplications.filter(
- (application) => application.handleResult === 0 && !accessedGroupApplications.includes(
- `${application.userID}_${application.createTime}`)
- ).length;
- const total = unHandleFriendApplicationNum + unHandleGroupApplicationNum;
- if (total) {
- uni.setTabBarBadge({
- index: 0,
- text: total < 99 ? total + '' : '99+'
- });
- } else {
- uni.removeTabBarBadge({
- index: 0
- });
- }
- this.$store.commit('contact/SET_UNHANDLE_FRIEND_APPLICATION_NUM', unHandleFriendApplicationNum);
- this.$store.commit('contact/SET_UNHANDLE_GROUP_APPLICATION_NUM', unHandleGroupApplicationNum);
- },
- deep: true
- }
- }
- };
- </script>
- <style lang="scss">
- /*每个页面公共css */
- @import '@/uni_modules/uview-plus/index.scss';
- /*#ifndef APP-NVUE*/
- view {
- box-sizing: border-box;
- }
- .ellipsis {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .ellipsis2 {
- overflow: hidden;
- text-overflow: ellipsis;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
- }
- uni-modal {
- z-index: 1100;
- }
- // 猜你喜欢样式
- .like-box {
- display: flex;
- align-items: center;
- justify-content: center;
- image {
- height: 40upx;
- width: 40upx;
- }
- .text {
- font-size: 28upx;
- color: #000;
- font-weight: bold;
- margin: 0 10upx;
- }
- }
- .no-data-box {
- height: 100%;
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- flex-direction: column;
- image {
- width: 264upx;
- height: 212upx;
- }
- .empty-title {
- margin-top: 20rpx;
- font-size: 28rpx;
- color: gray;
- }
- }
- .doctor-box {
- margin-top: 15rpx;
- padding: 20rpx 0rpx 0rpx;
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: flex-start;
- .doctor {
- width: 100%;
- margin-bottom: 15rpx;
- background: #f9f8fe;
- padding: 15rpx;
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: flex-start;
- &:last-child {
- margin-bottom: 0rpx;
- }
- .item {
- width: 100%;
- display: flex;
- align-items: flex-start;
- justify-content: flex-start;
- .left {
- .head-box {
- width: 92rpx;
- height: 92rpx;
- position: relative;
- .isline {
- width: 92rpx;
- height: 92rpx;
- border-radius: 50%;
- border: 2rpx solid #e69a22;
- display: flex;
- align-items: center;
- justify-content: center;
- position: absolute;
- bottom: 0rpx;
- .img {
- position: absolute;
- bottom: 1rpx;
- width: 75rpx;
- height: 35rpx;
- image {
- width: 75rpx;
- height: 35rpx;
- }
- .name {
- width: 75rpx;
- height: 35rpx;
- bottom: -3rpx;
- text-align: center;
- position: absolute;
- font-size: 16upx;
- font-family: PingFang SC;
- font-weight: bold;
- color: #ffffff;
- }
- }
- }
- .doc-img {
- border-radius: 50%;
- width: 100%;
- height: 100%;
- }
- }
- }
- .right {
- width: calc(100% - 100rpx);
- margin-left: 20rpx;
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: flex-start;
- .doc-box {
- display: flex;
- align-items: center;
- justify-content: space-between;
- .doc-name {
- font-size: 32upx;
- font-family: PingFang SC;
- font-weight: bold;
- color: #111111;
- }
- .doc-position {
- margin-left: 16rpx;
- font-size: 26upx;
- font-weight: bold;
- font-family: PingFang SC;
- color: #2a2b2e;
- }
- .doc-dept {
- margin-left: 16rpx;
- font-size: 26upx;
- font-weight: bold;
- font-family: PingFang SC;
- color: #2a2b2e;
- }
- }
- .hospital-box {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- margin-top: 10rpx;
- .tag {
- display: flex;
- align-items: center;
- justify-content: center;
- background-color: #4fc06b;
- border-radius: 10rpx;
- padding: 5rpx 10rpx;
- font-size: 20upx;
- font-weight: bold;
- font-family: PingFang SC;
- color: #ffffff;
- }
- .name {
- margin-left: 6rpx;
- font-size: 26upx;
- font-weight: bold;
- font-family: PingFang SC;
- color: #2a2b2e;
- }
- }
- .doc-spec {
- width: 100%;
- display: flex;
- align-items: center;
- justify-content: flex-start;
- margin-top: 15rpx;
- .spec {
- font-size: 26upx;
- font-family: PingFang SC;
- color: #626468;
- }
- }
- .doc-count {
- margin-top: 15rpx;
- display: flex;
- align-items: center;
- justify-content: flex-start;
- .name {
- font-size: 24upx;
- font-family: PingFang SC;
- color: #9b9b9b;
- }
- .count {
- margin: 0rpx 5rpx;
- font-size: 24upx;
- font-family: PingFang SC;
- color: #2a2b2e;
- }
- }
- .doc-price {
- width: 100%;
- margin-top: 15rpx;
- display: flex;
- align-items: center;
- justify-content: flex-start;
- .btn {
- display: flex;
- align-items: center;
- justify-content: center;
- background-color: #feefd7;
- padding: 15rpx 30rpx;
- border-radius: 30rpx;
- font-size: 26upx;
- font-family: PingFang SC;
- color: #e69a22;
- }
- }
- }
- }
- }
- }
- /*#endif*/
- </style>
- <style lang="less">
- /*每个页面公共css */
- // @import './assets/iconfont/iconfont.css';
- @import './assets/css/common.less';
- /* 全局flex样式 */
- @import './common/css/flexCommon.css';
- /*引入全局补充样式*/
- @import './assets/css/czy/es.1.base.css';
- @import './assets/css/czy/es.2.color.css';
- @import './assets/css/czy/es.3.icon.css';
- @import './assets/css/czy/es.4.view.css';
- @import './common/css/frame.css';
- .textOne {
- overflow: hidden;
- white-space: nowrap;
- text-overflow: ellipsis;
- }
- .textTwo {
- overflow: hidden;
- text-overflow: ellipsis;
- display: -webkit-box;
- -webkit-line-clamp: 2;
- -webkit-box-orient: vertical;
- }
- </style>
|