Browse Source

分支合并

lianbingjie 2 years ago
parent
commit
a62e0fa67c

+ 9 - 1
src/config.json

@@ -380,5 +380,13 @@
         "expurasingtime":true,
         "winnerMap":true
     },
-    "keywordsLimitNologin":25
+    "keywordsLimitNologin":25,
+	"messageCenter": {
+		"appid": "10000",
+        "dbName": "messagetest",
+        "interval": 300,
+        "createtime": "2023-01-04 00:00:00",
+        "limitDay": 7,
+        "limitCount": 3
+    }
 }

+ 3 - 0
src/jfw/front/swordfish.go

@@ -87,6 +87,9 @@ func (m *Front) PcAjaxReq() {
 	baseUserId := m.GetSession("base_user_id")
 	currentPage, _ := m.GetInteger("pageNumber")
 	pageSize, _ := m.GetInteger("pageSize")
+	if pageSize == 0 {
+		pageSize = 50
+	}
 	if tabularflag == "Y" && userId == "" {
 		//判断用户是否登录进行表格查询,否则返回基本数据
 		tabularflag = ""

+ 74 - 0
src/jfw/front/websocket.go

@@ -3,6 +3,7 @@ package front
 import (
 	"encoding/json"
 	"fmt"
+	. "jy/src/jfw/config"
 	"log"
 	"strings"
 	"sync"
@@ -320,3 +321,76 @@ func QrToShareTimeline(conn *websocket.Conn) {
 		}
 	}
 }
+
+//pc弹框 最新一条消息
+func GetBuoyMsg(conn *websocket.Conn) {
+	defer qutil.Catch()
+	sess := xweb.RootApp().SessionManager.Session(conn.R, conn.W)
+	userid, _ := sess.Get("userId").(string)
+	if userid == "" {
+		return
+	}
+	messageCenter, _ := Sysconfig["messageCenter"].(map[string]interface{})
+	appid, _ := messageCenter["appid"].(string)
+	dbName, _ := messageCenter["dbName"].(string)
+	createtime := qutil.ObjToString(messageCenter["createtime"])
+	interval := qutil.IntAllDef(messageCenter["interval"], 300)
+	limitCount := qutil.IntAllDef(messageCenter["limitCount"], 3)
+	go func() {
+		defer qutil.Catch()
+		for {
+			var receive string
+			err := websocket.Message.Receive(conn, &receive)
+			if err != nil {
+				//log.Println("websocket接收失败!", err)
+				return
+			}
+			if receive == "close" { //关闭
+				return
+			} else if receive == "HeartBeat" { //心跳监测
+				websocket.Message.Send(conn, "HeartBeat")
+			}
+		}
+	}()
+	//发送消息
+	counter := 0
+	isFirst := true
+	for {
+		counter++
+		if counter%5 == 0 {
+			if err := websocket.Message.Send(conn, "HeartBeat"); err != nil {
+				conn.Close()
+				return
+			}
+		}
+		if isFirst || counter >= interval {
+			counter = 0
+			timeA := time.Now().AddDate(0, 0, -qutil.IntAllDef(messageCenter["limitDay"], 7))
+			timeB, err := time.ParseInLocation(qutil.Date_Full_Layout, createtime, time.Local)
+			if err == nil && timeA.After(timeB) {
+				createtime = qutil.FormatDate(&timeA, qutil.Date_Full_Layout)
+			}
+			list := public.BaseMysql.SelectBySql(`select id,title,link,content,show_content,pc_tip,isdel,isRead from `+dbName+`.message where receive_userid=? and appid=? and createtime>? order by createtime desc limit ?`, userid, appid, createtime, limitCount)
+			if list != nil {
+				for _, v := range *list {
+					if qutil.IntAll(v["pc_tip"]) == 1 || qutil.IntAll(v["isdel"]) != 1 || qutil.IntAll(v["isRead"]) == 1 {
+						continue
+					}
+					id := qutil.Int64All(v["id"])
+					reply := fmt.Sprintf(`{"id":%d,"title":"%s","content":"%s","show_content":"%s","link":"%s"}`, id, qutil.ObjToString(v["title"]), qutil.ObjToString(v["content"]), qutil.ObjToString(v["show_content"]), strings.Split(qutil.ObjToString(v["link"]), ",")[0])
+					if err := websocket.Message.Send(conn, reply); err != nil {
+						//log.Println("websocket发送失败!", err)
+						conn.Close()
+						return
+					}
+					if id > 0 {
+						public.BaseMysql.UpdateOrDeleteBySql(`update `+dbName+`.message set pc_tip=1 where id=?`, id)
+					}
+					time.Sleep(time.Second)
+				}
+			}
+		}
+		isFirst = false
+		time.Sleep(time.Second)
+	}
+}

+ 1 - 0
src/jfw/modules/app/src/web/templates/frontRouter/verify/free/index.html

@@ -139,6 +139,7 @@
     <script src=//cdn-common.jianyu360.com/cdn/lib/vue/2.6.11/vue.min.js></script>
     <script src=//cdn-common.jianyu360.com/cdn/lib/vant/2.12.24/lib/vant.min.js></script>
     <script src=//cdn-common.jianyu360.com/cdn/lib/zepto/1.2.0/zepto.min.js></script>
+    <script src='{{Cdns .Host "seo" "cdn"|SafeUrl}}/jyapp/js/common.js?v={{Msg "seo" "version"}}'></script>
     <!--E-当前页面的资源-->
     {{include "/big-member/commonjs.html"}}
     <script src='{{Cdns .Host "seo" "cdn"|SafeUrl}}/common-module/account/js/verify.js?v={{Msg "seo" "version"}}'></script>

+ 1 - 0
src/main.go

@@ -83,6 +83,7 @@ func main() {
 	mux1.Handle("/ws", websocket.Handler(front.ServeWss))
 	mux1.Handle("/qrToLab", websocket.Handler(front.QrToLabWss))
 	mux1.Handle("/webscoket/qrToShareTimeline", websocket.Handler(front.QrToShareTimeline))
+	mux1.Handle("/webscoket/getBuoyMsg", websocket.Handler(front.GetBuoyMsg))
 	xweb.RunBase(":"+Sysconfig["webport"].(string), mux1)
 }
 

+ 7 - 3
src/web/staticres/common-module/account/js/verify.js

@@ -260,13 +260,17 @@ var vNode = {
                       window.parent.postMessage({
                           action: 'success'
                       }, location.origin)
-                  } else if (_this.act == 'logout') {
-                      try {
+                  } else if (_this.act == 'logout' || !document.referrer) {
+                      if (utils.isWeiXinBrowser) {
+                        location.replace('/jy_mobile/tabbar/home')
+                      } else {
+                        try {
                           JyObj.backUrl('H')
                           JyObj.refreshAppointTab('subscribe', 1)
                           JyObj.refreshAppointTab('box', 1)
                           JyObj.refreshAppointTab('me', 1)
-                      } catch (error) {}
+                        } catch (error) {}
+                      }
                   } else if (_this.redirectTo) {
                       location.replace(_this.redirectTo)
                   } else {

+ 77 - 2
src/web/staticres/common-module/ad/js/msgbuoy.js

@@ -8,7 +8,7 @@
 
 var getMsgBuoyActive = {
   // 版本号
-  version: '0.0.1',
+  version: '0.0.2',
   platform: '', // work_bench、wx、app、pc
   msgids: '',
   floatDOM: '',
@@ -23,6 +23,7 @@ var getMsgBuoyActive = {
         this.getBuoyMsgAjax()
       }
     } else {
+      this.listenNotification()
       this.getBuoyMsgAjax()
     }
   },
@@ -384,8 +385,82 @@ var getMsgBuoyActive = {
     } else if (isAndroid) {
       return 'Android'
     }
-  }
+  },
+  /**
+   * @date 2023/1/4 消息通知改为 webscoket 获取并调用浏览器消息通知
+   */
+  listenNotification () {
+    /**
+     * 进行浏览器通知,判断上次通知是否与当前一致,一致则不进行重复通知
+     * @param datas - 信息数据
+     */
+    function sendNotification (datas) {
+      var waitShowMessageId = localStorage.getItem('notification-login-clear-info') || -1
+      if (waitShowMessageId === datas.id) {
+        return console.warn('重复消息ID,不进行重复通知')
+      }
+      try {
+        Notification.requestPermission(function(status) {
+          var notifyStatus = Notification.permission || status
+          if(notifyStatus === 'granted'){
+            localStorage.setItem('notification-login-clear-info', datas.id)
+            var notify = new Notification(datas.title,{
+              icon: '/images/t3_new.jpg',
+              body: datas.show_content || datas.content || ''
+            })
+            // 点击时桌面消息时触发
+            notify.onclick = function () {
+              try {
+                getMsgBuoyActive.istoReaded(datas.id)
+                notify.close()
+                switch (getMsgBuoyActive.platformOS()) {
+                  case 'pc':
+                    location.href = '/swordfish/frontPage/messageCenter/sess/index'
+                    break;
+                  case 'work_bench':
+                    window.open('/swordfish/frontPage/messageCenter/sess/index')
+                    break;
+                }
+              } catch (e) {
+                console.warn(e)
+              }
+            }
+          } else {
+            Notification.requestPermission(function () {
+              sendNotification(datas)
+            })
+          }
+        })
+      } catch (e) {
+        console.warn('不支持通知')
+      }
+    }
 
+    // 定义 scoket 信息
+    var pushMessageScoket = {
+      url: "ws"+(!isIE9&&"https:"==document.location.protocol?"s":"")+"://"+window.location.host,
+      init: function () {
+        if (typeof CommonWebScoket === 'function') {
+          this._scoket = new CommonWebScoket(this.url + '/webscoket/getBuoyMsg', '', {
+            ajaxReq: function() {},
+            complete: function (data, type) {
+              try {
+                var pushMessage = JSON.parse(data)
+                if (pushMessage.id) {
+                  sendNotification(pushMessage)
+                }
+              } catch (e) {
+                console.warn(e)
+              }
+            }
+          }).init()
+        }
+      }
+    }
+
+    // 初始化
+    pushMessageScoket.init()
+  }
 }
 
 // 初始化

+ 10 - 49
src/web/staticres/js/login.js

@@ -445,57 +445,18 @@ function toReaded(ids, type, url) {
         }
     })
 }
+
+/**
+ * @date 2023/1/4 消息通知改为 webscoket 获取并调用浏览器消息通知
+ */
 // 查看是否有新消息
 function checkCounts() {
   try {
-    Notification.requestPermission(function(status) {
-      if(status === 'granted'){
-        var str = window.location.href
-        var arr = str.split('https://')[1].split('/')[1]
-        if (arr) {
-          clearInterval(msgTimer)
-          return
-        }
-        clearInterval(msgTimer)
-        msgTimer = setInterval(function () {
-          $.ajax({
-            type: 'POST',
-            url: '/jymessageCenter/lastNewMessage?t=' + Date.now(),
-            success: function (r) {
-              if (r.error_code == 1001) {
-                clearInterval(msgTimer)
-                return
-              }
-              var num = r.count
-              var datas = r.data
-              // var noMesgs = window.localStorage.setItem('noMesg', num)
-              // if (num !== noMesgs && !$.isEmptyObject(datas)) {
-              if (!$.isEmptyObject(datas) && datas !=="") {
-                var notify = new Notification(datas.title,{
-                  icon: '../images/t3_new.jpg',
-                  body: datas.content
-                })
-                // 点击时桌面消息时触发
-                notify.onclick = function () {
-                  if (r.data.isRead == 0) {
-                    toReaded(r.data.id, r.data.msg_type, r.data.link)
-                  }
-                }
-              }
-              window.localStorage.setItem('noMesg', num)
-            },
-            error: function () {
-              clearInterval(msgTimer)
-            }
-          })
-        }, 300000)
-      } else {
-        Notification.requestPermission()
-      }
-    })
-  } catch (e) {
-    console.log('不支持通知')
-  }
+    // 非工作台模式下需要重建链接,工作台嵌入页面不需要额外初始化
+    if (!goTemplateData.inIframe) {
+      getMsgBuoyActive.listenNotification()
+    }
+  } catch (e) {}
 }
 
 //查询用户信息,响应页面登录信息
@@ -776,7 +737,7 @@ var haslogin = function(num,kyorpn,url){
 			    window.location.href = "/?nol=2";
 				return;
 			}
-      
+
 			loginflag = true;
       // TODO login callback
       try {