| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236 |
- <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 {
- // initMaOpenIdNavigationInterceptor,
- // refreshUserInfoAfterBind,
- // checkMaOpenIdBind
- // } from '@/utils/maOpenIdInterceptor.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.klbycp.com'
- export default {
- globalData: {
- wsUrl: 'ws://webim.klbycp.com',
- danmuWSUrl: 'wss://webim.klbycp.com',
- aiWSUrl: 'ws://webim.klbycp.com',
- kfurl: 'https://work.weixin.qq.com/kfid/kfc3731c5008ebd8906', //企业微信客服链接
- corpId: 'ww70ac72e824957fc9', //客服企业id
- miniprogamId: 'gh_b51445318864',
- bindMiniProgramPath: '/pages/auth/bindApp',
- shareCorpId: '', // 分享企业id
- shareSchema: "", // 应用跳转标识,显示在具体应用下的 Schema字段
- shareAgentid: "", // 企业微信管理后台 应用唯一标识。显示在具体应用下的 AgentId字段
- shareAppid_gh: "", // 必须是应用关联的小程序,注意要有@app后缀
- privacyPolicy: "https://userapp.klbycp.com/web/getAgreementConfig?appId=wxecdaff01852ca309&agreementType=appPrivacyAgreement", //隐私政策
- userAgreement: "https://userapp.klbycp.com/web/getAgreementConfig?appId=wxecdaff01852ca309&agreementType=appUserAgreement", //用户协议
- baseUrl: baseUrl,
- activityId: 1,
- },
- onLaunch: function(options) {
- //initMaOpenIdNavigationInterceptor();
- 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);
- // setTimeout(() => {
- // checkMaOpenIdBind();
- // }, 800);
- //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()) {
- //refreshUserInfoAfterBind();
- //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: 3,
- text: total < 99 ? total + '' : '99+'
- });
- } else {
- uni.removeTabBarBadge({
- index: 3
- });
- }
- 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>
|