Browse Source

增加钉钉预警

wukai 1 year ago
parent
commit
8cc80416b4

+ 28 - 7
dayun-admin/pom.xml

@@ -37,7 +37,7 @@
             <version>1.6.2</version>
         </dependency>
 
-         <!-- Mysql驱动包 -->
+        <!-- Mysql驱动包 -->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
@@ -76,6 +76,27 @@
             <artifactId>spring-boot-test</artifactId>
             <scope>test</scope>
         </dependency>
+        <!--  -->
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>alibaba-dingtalk-service-sdk</artifactId>
+            <version>2.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpcore</artifactId>
+            <version>4.4.16</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.14</version>
+        </dependency>
     </dependencies>
 
     <build>
@@ -95,15 +116,15 @@
                     </execution>
                 </executions>
             </plugin>
-            <plugin>   
-                <groupId>org.apache.maven.plugins</groupId>   
-                <artifactId>maven-war-plugin</artifactId>   
-                <version>3.1.0</version>   
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>3.1.0</version>
                 <configuration>
                     <failOnMissingWebXml>false</failOnMissingWebXml>
                     <warName>${project.artifactId}</warName>
-                </configuration>   
-           </plugin>   
+                </configuration>
+            </plugin>
         </plugins>
         <finalName>${project.artifactId}</finalName>
     </build>

+ 15 - 0
dayun-admin/src/main/java/com/jjt/biz/controller/ApiController.java

@@ -22,6 +22,7 @@ import com.jjt.framework.websocket.WebSocketUsers;
 import org.apache.coyote.http11.upgrade.UpgradeInfo;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
@@ -56,6 +57,10 @@ public class ApiController extends BaseController {
     private IKeyInfoService keyInfoService;
     @Resource
     private IDeviceUpgradeService upgradeService;
+    @Resource
+    private DingTalkService dingTalkService;
+    @Resource
+    private RedisTemplate<String, Object> redisTemplate;
 
     /**
      * 设备注册接口
@@ -124,6 +129,11 @@ public class ApiController extends BaseController {
             wsMap.put("illegal", info.getIsIllegal());
             wsMap.put("keyword", info.getKeyType());
             WebSocketUsers.sendMessageToUsersByText(JSON.toJSONString(wsMap));
+            if ("Y".equals(info.getIsIllegal())) {
+                //如果是恶意动态,则发送钉钉预警
+                redisTemplate.opsForList().leftPush("nls:need_handler", wsMap);
+//                dingTalkService.sendMsg(wsMap);
+            }
         });
         return AjaxResult.success();
     }
@@ -193,6 +203,11 @@ public class ApiController extends BaseController {
             wsMap.put("illegal", info.getIsIllegal());
             wsMap.put("keyword", info.getKeyType());
             WebSocketUsers.sendMessageToUsersByText(JSON.toJSONString(wsMap));
+            if ("Y".equals(info.getIsIllegal())) {
+                //如果是恶意动态,则发送钉钉预警
+//                dingTalkService.sendMsg(wsMap);
+                redisTemplate.opsForList().leftPush("nls:need_handler", wsMap);
+            }
             bluetoothInfoService.insertBluetoothInfo(info);
         });
         return AjaxResult.success();

+ 115 - 0
dayun-admin/src/main/java/com/jjt/biz/service/DingTalkService.java

@@ -0,0 +1,115 @@
+package com.jjt.biz.service;
+
+import com.dingtalk.api.DefaultDingTalkClient;
+import com.dingtalk.api.DingTalkClient;
+import com.dingtalk.api.request.OapiRobotSendRequest;
+import com.dingtalk.api.response.OapiRobotSendResponse;
+import com.jjt.biz.domain.RealTimeInfoVO;
+import com.jjt.biz.domain.WifiInfo;
+import com.jjt.biz.mapper.WifiInfoMapper;
+import com.jjt.common.core.redis.RedisCache;
+import com.jjt.framework.web.domain.server.Sys;
+import com.jjt.system.service.ISysConfigService;
+import com.taobao.api.ApiException;
+import org.apache.commons.codec.binary.Base64;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * WIFI信息Service业务层处理
+ *
+ * @author ruoyi
+ * @date 2023-07-06
+ */
+@Service
+@EnableScheduling
+public class DingTalkService {
+    @Resource
+    private ISysConfigService sysConfigService;
+    @Resource
+    private RedisTemplate<String, Object> redisTemplate;
+
+    @Scheduled(cron = "0/5 * * * * ?")
+    public void sendMsg() {
+        List<Map<String, Object>> list = new ArrayList<>();
+        long s = System.currentTimeMillis();
+
+        while (true) {
+            //超过4秒,或者队列取空,则本次任务结束
+            if (System.currentTimeMillis() - s > 4000) {
+                break;
+            }
+            Object o = redisTemplate.opsForList().rightPop("nls:need_handler");
+            if (o == null) {
+                break;
+            } else {
+                Map<String, Object> map = (Map<String, Object>) o;
+                list.add(map);
+            }
+
+        }
+        try {
+            if (list.size() == 0) {
+                //如果队列中没有取到数据
+                return;
+            }
+            RedisCache cache = new RedisCache();
+//            cache.set
+            Long timestamp = System.currentTimeMillis();
+            String secret = sysConfigService.selectConfigByKey("dingtalk.scret");
+            String webhook = sysConfigService.selectConfigByKey("dingtalk.webhook");
+            String accessURL = sysConfigService.selectConfigByKey("web.access.url");
+
+            String stringToSign = timestamp + "\n" + secret;
+            Mac mac = Mac.getInstance("HmacSHA256");
+            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
+            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
+            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
+//            System.out.println(sign);
+
+            String uri = webhook + "&timestamp=" + timestamp + "&sign=" + sign;
+
+            DingTalkClient client = new DefaultDingTalkClient(uri);
+            OapiRobotSendRequest request = new OapiRobotSendRequest();
+            request.setMsgtype("markdown");
+            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
+            markdown.setTitle("恶意动态预警");
+            String text = "###恶意动态预警\n";
+            for (Map<String, Object> wsMap : list) {
+                String msgUrl = accessURL + "?t=" + timestamp;
+                msgUrl += "&type=" + wsMap.get("type");
+                msgUrl += "&name=" + URLEncoder.encode((String) wsMap.get("name"), "utf-8");
+                msgUrl += "&keyword=" + URLEncoder.encode((String) wsMap.get("keyword"), "utf-8");
+                Date time = (Date) wsMap.get("time");
+                msgUrl += "&time=" + time.getTime();
+                text += "> 发现类型为”" + wsMap.get("keyword") + "“的恶意" + wsMap.get("type") + "\t[位置](" + msgUrl + ") \n\n";
+            }
+            System.err.println(text);
+            markdown.setText(text);
+            request.setMarkdown(markdown);
+            OapiRobotSendResponse response = client.execute(request);
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException(e);
+        } catch (InvalidKeyException e) {
+            throw new RuntimeException(e);
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        } catch (ApiException e) {
+            throw new RuntimeException(e);
+        }
+    }
+}

+ 59 - 0
dayun-admin/src/test/java/DingTest.java

@@ -0,0 +1,59 @@
+import com.dingtalk.api.DefaultDingTalkClient;
+import com.dingtalk.api.DingTalkClient;
+import com.dingtalk.api.request.OapiRobotSendRequest;
+import com.dingtalk.api.response.OapiRobotSendResponse;
+import com.taobao.api.ApiException;
+import org.apache.commons.codec.binary.Base64;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.net.URLEncoder;
+import java.util.Arrays;
+
+public class DingTest {
+    public static void main(String[] args) throws Exception {
+        Long timestamp = System.currentTimeMillis();
+        String secret = "SEC7ff9d3d9424aaac7e33b928a50b6862adb608703a17c57aabd52a18d3339b1cd";
+
+        String stringToSign = timestamp + "\n" + secret;
+        Mac mac = Mac.getInstance("HmacSHA256");
+        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
+        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
+        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
+        System.out.println(sign);
+
+        String uri = "https://oapi.dingtalk.com/robot/send?access_token=34fc98f715e06836350f8b1ee9d2211b3eee2568a15a0ef161c7f55ec7874113&timestamp=" + timestamp + "&sign=" + sign;
+
+        DingTalkClient client = new DefaultDingTalkClient(uri);
+        OapiRobotSendRequest request = new OapiRobotSendRequest();
+//        request.setMsgtype("text");
+//        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
+//        text.setContent("测试文本消息");
+//        request.setText(text);
+//        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
+////        at.setAtMobiles(Arrays.asList("17760370787"));
+//// isAtAll类型如果不为Boolean,请升级至最新SDK
+//        at.setIsAtAll(true);
+////        at.setAtUserIds(Arrays.asList("109929", "32099"));
+//        request.setAt(at);
+
+//        request.setMsgtype("link");
+//        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
+//        link.setMessageUrl("http://8.142.173.95:18001/");
+//        link.setPicUrl("http://8.142.173.95:18001/static/img/logo.996775e0.png");
+//        link.setTitle("恶意动态预警");
+//        link.setText("有新的恶意,点击查看位置信息");
+//        request.setLink(link);
+//
+        request.setMsgtype("markdown");
+        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
+        markdown.setTitle("杭州天气");
+        String text="###恶意动态预警\n" +
+                "> 发现类型为”反动“的恶意蓝牙”测试“\t[位置](http://8.142.173.95:18001/?t=1689242765017&type=蓝牙&name=%E6%B5%8B%E8%AF%95&keyword=%E5%8F%8D%E5%8A%A8&time=1688549244000) \n\n" +
+                "> 发现类型为”反动“的恶意WIFI”法轮大法好哇“\t[位置](http://8.142.173.95:18001/?t=1689242765017&type=WIFI&name=%E6%B3%95%E8%BD%AE%E5%8A%9F%E5%A5%BD%E5%93%87&keyword=%E5%8F%8D%E5%8A%A8&time=1688549244000) ";
+        markdown.setText(text);
+        request.setMarkdown(markdown);
+        OapiRobotSendResponse response = client.execute(request);
+        response.isSuccess();
+    }
+}

+ 56 - 0
dayun-admin/src/test/java/RedisTest.java

@@ -0,0 +1,56 @@
+import com.jjt.RuoYiApplication;
+import com.jjt.common.core.redis.RedisCache;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = RuoYiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class RedisTest {
+    @Resource
+    private RedisCache cache;
+
+    @Test
+    public void test() {
+        List<String> list = new ArrayList<>();
+        list.add("1");
+        list.add("2");
+        list.add("3");
+        cache.setCacheList("dingList", list);
+        Thread t2 = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                for (int i = 0; i < 100; i++) {
+                    cache.redisTemplate.opsForList().leftPush("nls:need_handler", "this " + i);
+                }
+            }
+        });
+        Thread t4 = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                for (int i = 1000; i < 2000; i++) {
+                    cache.redisTemplate.opsForList().leftPush("nls:need_handler", "this " + i);
+                }
+            }
+        });
+
+        Thread t3 = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                while (cache.redisTemplate.opsForList().size("nls:need_handler") > 0) {
+                    String xx = (String) cache.redisTemplate.opsForList().rightPop("nls:need_handler");
+                    System.err.println(xx);
+                }
+            }
+        });
+        t4.start();
+        t2.start();
+        t3.start();
+    }
+}