zhoufan 1 rok temu
rodzic
commit
a453008a48

+ 1 - 1
midware-api/src/main/java/midware/controller/HomeController.java

@@ -46,7 +46,7 @@ public class HomeController extends BaseController {
46 46
 
47 47
     @GetMapping("/test")
48 48
     public AjaxResult Test() {
49
-        //TtsHelper.TextToSpeech("你好,世界");
49
+        //TtsHelper.TextToSpeech("你好,8 0 0 1");
50 50
         //String a=client.sendAsyncApiCommand("originate", "{origination_caller_id_number=12345}user/1001 &playback(/home/free_anzhuanglujing/wav/welcome.wav)");
51 51
         //EslMessage a=client.sendSyncApiCommand("sofia status profile internal reg\n\n","") ;
52 52
         //String a=eslClientService.extenCall("1001","1010");

+ 59 - 36
midware-service/src/main/java/midware/service/eslclient/EslEventListener.java

@@ -269,7 +269,7 @@ public class EslEventListener implements IEslEventListener {
269 269
                     if (chan != null && !chan.isAnswer()) {
270 270
                         chan.setAnswer(true);
271 271
                         //呼出号码应答通知坐席
272
-                        if (session.getType() == 2) {
272
+                        if (session != null && session.getType() == 2) {
273 273
                             if (!EslCommon.sessionOpera.containsKey(chanNames[2])) {
274 274
                                 try {
275 275
                                     Thread.sleep(300);
@@ -301,25 +301,48 @@ public class EslEventListener implements IEslEventListener {
301 301
                                 if (callerAgent != null) callerAgent.setAgentState(EslAgentNum.talking.ordinal());
302 302
                             }
303 303
 
304
-                            session.setAnswer(true);
305
-
306 304
                             String ext = callerNum;
307
-                            if (session.getType() == 1) {
308
-                                ext = calleeNum;
305
+                            if (session.getType() == 1) ext = calleeNum;
306
+
307
+                            String sid = session.getSessionId(), cid = chan.getChanId();
308
+
309
+                            String codec = header.get("variable_ep_codec_string");
310
+                            if(codec.contains("H264")){
311
+                                //视频
312
+                                session.setVideo(true);
313
+                                if(session.isMeeting()){
314
+                                    chan.setRecordPath(session.getVideoPath());
315
+                                }else {
316
+                                    String parentPath = "files/video/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + ext;
317
+                                    File file = new File(parentPath);
318
+                                    if (!file.exists()) file.mkdirs();
319
+                                    String filePath = parentPath + "/" + cid + ".mp4";
320
+                                    chan.setRecordPath(filePath);
321
+                                    String recordPath = file.getAbsolutePath() + "/" + cid + ".mp4";
322
+
323
+                                    Channel channel = EslCommon.channels.stream().filter(p -> p.getSessionId().equals(sid)
324
+                                            && !p.getChanId().equals(cid)).findFirst().get();
325
+                                    eslClientService.record(channel.getChanId(), recordPath);
326
+
327
+                                    eslClientService.record(cid, recordPath);
328
+                                }
329
+                            } else {
330
+                                //录音
331
+                                String parentPath = "files/luyin/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + ext;
332
+                                File file = new File(parentPath);
333
+                                if (!file.exists()) file.mkdirs();
334
+                                String filePath = parentPath + "/" + cid + ".wav";
335
+                                chan.setRecordPath(filePath);
336
+                                String recordPath = file.getAbsolutePath() + "/" + cid + ".wav";
337
+                                eslClientService.record(cid, recordPath);
309 338
                             }
310
-                            //录音
311
-                            String parentPath = "files/luyin/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + ext;
312
-                            File file = new File(parentPath);
313
-                            if (!file.exists()) file.mkdirs();
314
-                            String filePath = parentPath + "/" + chan.getChanId() + ".wav";
315
-                            chan.setRecordPath(filePath);
316
-                            String recordPath = file.getAbsolutePath() + "/" + chan.getChanId() + ".wav";
317
-                            eslClientService.record(chan.getChanId(), recordPath);
318 339
 
319 340
                             uw = new LambdaUpdateWrapper<>();
320 341
                             uw.set(Record::getRecordPath, chan.getRecordPath());
321 342
                             uw.eq(Record::getId, chan.getRecordId()).set(Record::getAnswerTime, new Date()).set(Record::getIsAnswer, 1);
322 343
                             iRecordService.updateBatch(uw);
344
+
345
+                            session.setAnswer(true);
323 346
                         }
324 347
                     }
325 348
                     break;
@@ -339,26 +362,26 @@ public class EslEventListener implements IEslEventListener {
339 362
                     String sid = chan.getSessionId();
340 363
                     if (session == null) session = EslCommon.getSessionById(sid);
341 364
 
365
+                    //呼出号码未接通挂断通知坐席
366
+                    if (session != null && session.getType() == 2 && !chan.isAnswer()) {
367
+                        if (!EslCommon.sessionOpera.containsKey(calleeNum)) {
368
+                            try {
369
+                                Thread.sleep(300);
370
+                            } catch (InterruptedException e) {
371
+                                throw new RuntimeException(e);
372
+                            }
373
+                        }
374
+                        if (EslCommon.sessionOpera.containsKey(calleeNum)) {
375
+                            String[] values = EslCommon.sessionOpera.get(calleeNum).split("\\|");
376
+                            EslCommon.sessionOpera.remove(calleeNum);
377
+                            actionNotice(values[0], values[1], sid, false);
378
+                        }
379
+                    }
380
+
342 381
                     boolean isupdate = true;
343 382
                     //分机通道修改坐席状态
344 383
                     if (chan.getType() == 1) {
345 384
                         if (agent != null) {
346
-                            //呼出号码未接通挂断通知坐席
347
-                            if (session != null && session.getType() == 2 && !chan.isAnswer()) {
348
-                                if (!EslCommon.sessionOpera.containsKey(chanNames[2])) {
349
-                                    try {
350
-                                        Thread.sleep(300);
351
-                                    } catch (InterruptedException e) {
352
-                                        throw new RuntimeException(e);
353
-                                    }
354
-                                }
355
-                                if (EslCommon.sessionOpera.containsKey(chanNames[2])) {
356
-                                    String[] values = EslCommon.sessionOpera.get(chanNames[2]).split("\\|");
357
-                                    EslCommon.sessionOpera.remove(chanNames[2]);
358
-                                    actionNotice(values[0], values[1], sid, false);
359
-                                }
360
-                            }
361
-
362 385
                             String agentNo = agent.getAgent();
363 386
                             if (session.getType() == 1 && chan.isAnswer()) {//呼入接通后挂断-话后处理
364 387
                                 agent.setAgentState(EslAgentNum.aftertalk.ordinal());
@@ -496,10 +519,10 @@ public class EslEventListener implements IEslEventListener {
496 519
                         agent.setAgentState(EslAgentNum.busy.ordinal());
497 520
                         break;
498 521
                     case "ForceWorkOn"://强制置闲
499
-                        agent.setAgentState(EslAgentNum.free.ordinal());
500
-                        break;
501 522
                     case "ForceWorkOff"://强制置忙
502
-                        agent.setAgentState(EslAgentNum.busy.ordinal());
523
+                        Agent tagent = EslCommon.getAgent(values[2]);
524
+                        if (type.equals("ForceWorkOn")) tagent.setAgentState(EslAgentNum.free.ordinal());
525
+                        else tagent.setAgentState(EslAgentNum.busy.ordinal());
503 526
                         break;
504 527
                     case "HoldOn"://开启保持
505 528
                         break;
@@ -529,9 +552,9 @@ public class EslEventListener implements IEslEventListener {
529 552
                     case "Break"://强拆
530 553
                         break;
531 554
                 }
532
-            }else{
533
-                if(type.equals("Login")){
534
-                    if(agent!=null) {
555
+            } else {
556
+                if (type.equals("Login")) {
557
+                    if (agent != null) {
535 558
                         SpringHelper.getBean(EslClientService.class).logout(agentId, agent.getGroup());
536 559
                         EslCommon.agents.remove(agent);
537 560
                     }
@@ -539,7 +562,7 @@ public class EslEventListener implements IEslEventListener {
539 562
             }
540 563
             EslCommon.sessionOpera.remove(uuid);
541 564
             if (isEnd) {
542
-                actionNotice(type, agentId,"", bodys.startsWith("+OK"));
565
+                actionNotice(type, agentId, "", bodys.startsWith("+OK"));
543 566
             }
544 567
         }
545 568
         if (!bodys.startsWith("+OK")) {

+ 1 - 1
midware-service/src/main/java/midware/service/eslclient/entity/Channel.java

@@ -25,7 +25,7 @@ public class Channel {
25 25
     //是否接听
26 26
     private boolean isAnswer = false;
27 27
     //录音路径
28
-    private String recordPath;
28
+    private String recordPath = "";
29 29
     // 会话排序
30 30
     private long sessionSort = 0;
31 31
     //创建时间

+ 4 - 0
midware-service/src/main/java/midware/service/eslclient/entity/Session.java

@@ -16,6 +16,10 @@ public class Session {
16 16
     private boolean isAnswer = false;
17 17
     //是否会议
18 18
     private boolean isMeeting = false;
19
+    //是否视频
20
+    private boolean isVideo = false;
21
+    //视频路径
22
+    private String videoPath;
19 23
     //创建时间
20 24
     private Date createTime;
21 25
 }

+ 42 - 14
midware-service/src/main/java/midware/service/init/EslClientService.java

@@ -21,6 +21,8 @@ import org.springframework.stereotype.Service;
21 21
 import javax.annotation.PostConstruct;
22 22
 import javax.annotation.PreDestroy;
23 23
 import java.io.File;
24
+import java.text.SimpleDateFormat;
25
+import java.util.Date;
24 26
 import java.util.concurrent.ScheduledThreadPoolExecutor;
25 27
 import java.util.concurrent.TimeUnit;
26 28
 import java.util.stream.Stream;
@@ -74,7 +76,8 @@ public class EslClientService {
74 76
             scanExten();
75 77
 
76 78
             //设置中间件根目录
77
-            client.sendAsyncApiCommand(EslCommandEnum.global_setvar.name(), "md_base_dir=" + new File("").getAbsolutePath());
79
+            String path=new File("").getAbsolutePath();
80
+            client.sendAsyncApiCommand(EslCommandEnum.global_setvar.name(), "md_base_dir=" +path );
78 81
         }
79 82
     }
80 83
 
@@ -208,8 +211,8 @@ public class EslClientService {
208 211
         String result = "";
209 212
         try {
210 213
             String command = EslCommandEnum.originate.name();
211
-            String arg = " {origination_caller_id_number=" + callerNum + ",call_called=" + calleeNum
212
-                    + "}user/" + callerNum + " &bridge(" + getCallString(calleeNum)+")";
214
+            String arg = " {origination_caller_id_number=" + callerNum + ",call_called=" + calleeNum+",record_concat_video=true"
215
+                    + ",transfer_ringback=local_stream://moh}user/" + callerNum + " &bridge(" + getCallString(calleeNum)+")";
213 216
             result = client.sendAsyncApiCommand(command, arg);
214 217
 
215 218
         } catch (Exception e) {
@@ -223,7 +226,8 @@ public class EslClientService {
223 226
         String result = "";
224 227
         try {
225 228
             String command = EslCommandEnum.uuid_broadcast.name();
226
-            String arg = chanId + " att_xfer::{origination_caller_id_number=" + callerNum + "}" + getCallString(calleeNum);
229
+            String arg = chanId + " att_xfer::{origination_caller_id_number=" + callerNum
230
+                    + ",call_called=" + calleeNum + "}" + getCallString(calleeNum);
227 231
             result = client.sendAsyncApiCommand(command, arg);
228 232
             
229 233
         } catch (Exception e) {
@@ -262,12 +266,12 @@ public class EslClientService {
262 266
     }
263 267
 
264 268
     //监听
265
-    public String listen(String callerNum, String sessionId) {
269
+    public String listen(String callerNum,String calleeNum, String sessionId) {
266 270
         String result = "";
267 271
         try {
268 272
             String command = EslCommandEnum.originate.name();
269 273
             String arg = " {origination_caller_id_number=" + callerNum+ ",cc_member_session_uuid=" + sessionId
270
-                    + "}user/" + callerNum + " &eavesdrop(" + sessionId + ")";
274
+                    + ",call_called=" + calleeNum+ "}user/" + callerNum + " &eavesdrop(" + sessionId + ")";
271 275
             result = client.sendAsyncApiCommand(command, arg);
272 276
             
273 277
         } catch (Exception e) {
@@ -302,8 +306,15 @@ public class EslClientService {
302 306
 
303 307
             String command = EslCommandEnum.uuid_broadcast.name();
304 308
             //String path = "/home/wav/8001.wav";
305
-            String path = TtsHelper.TextToSpeechAgent("你好," + agent + "号话务员为您服务", agent);
306
-            String arg = chanId + " playback::" + path+ " both";
309
+
310
+            String at = agent;
311
+            try {
312
+                Integer.parseInt(agent);
313
+                at = agent.replaceAll("(.)", " $1").substring(1);
314
+            } catch (Exception ex) { }
315
+
316
+            String path = TtsHelper.TextToSpeechAgent("你好," + at + "号话务员为您服务", agent);
317
+            String arg = chanId + " playback::" + path + " both";
307 318
 
308 319
             result = client.sendAsyncApiCommand(command, arg);
309 320
 
@@ -318,11 +329,16 @@ public class EslClientService {
318 329
         String result = "";
319 330
         try {
320 331
             String command = EslCommandEnum.uuid_transfer.name();
321
-//            String arg = sessionId + " -both " + sessionId + " xml ExtenMeeting";
322
-            String arg = sessionId + " -both 'set:hangup_after_bridge=false,conference:" + sessionId + "@threeway' inline";
332
+            //String arg = sessionId + " -both " + sessionId + " xml ExtenMeeting";
333
+
334
+            String at = "threeway";
335
+            Session session = EslCommon.getSessionById(sessionId);
336
+            if (session != null && session.isVideo()) at = "video-mcu-stereo";
337
+            String arg = sessionId + " -both 'set:hangup_after_bridge=false,"
338
+                    + "conference:" + sessionId + "@" + at + "' inline";
323 339
             result = client.sendAsyncApiCommand(command, arg);
324 340
         } catch (Exception e) {
325
-            log.error( sessionId + " 会话加入会议失败", e);
341
+            log.error(sessionId + " 会话加入会议失败", e);
326 342
         }
327 343
         return result;
328 344
     }
@@ -332,9 +348,20 @@ public class EslClientService {
332 348
         String result = "";
333 349
         try {
334 350
             String command = EslCommandEnum.originate.name();
335
-            String arg = " {origination_caller_id_number=" + callerNum + ",cc_member_session_uuid=" + meetingId + "}"
351
+            String at = "threeway", argstr = "";
352
+            Session session = EslCommon.getSessionById(meetingId);
353
+            if (session != null && session.isVideo()) {
354
+                at = "video-mcu-stereo";
355
+                String parentPath = "files/video/meeting/" + new SimpleDateFormat("yyyyMMdd").format(new Date());
356
+                String path = new File(parentPath).getAbsolutePath()+ "/" + meetingId + ".mp4";
357
+                session.setVideoPath(parentPath+ "/" + meetingId + ".mp4");
358
+                argstr = ",record_concat_video=true,conference_auto_record=" + path;
359
+            }
360
+
361
+            String arg = " {origination_caller_id_number=" + callerNum + ",cc_member_session_uuid=" + meetingId
362
+                    + ",call_called=" + calleeNum + argstr + "}"
336 363
                     //+ getCallString(calleeNum) + " " + meetingId + " xml ExtenMeeting";
337
-                    + getCallString(calleeNum) + " &conference(" + meetingId + "@threeway)";
364
+                    + getCallString(calleeNum) + " &conference(" + meetingId + "@" + at + ")";
338 365
             result = client.sendAsyncApiCommand(command, arg);
339 366
 
340 367
         } catch (Exception e) {
@@ -409,7 +436,8 @@ public class EslClientService {
409 436
         try {
410 437
             String command = EslCommandEnum.uuid_transfer.name();
411 438
             //String arg = chanId + " " + calleeNum + " xml ForExten";
412
-            String arg = chanId + " 'set:hangup_after_bridge=false,bridge:{origination_caller_id_number=" + callerNum + "}" + getCallString(calleeNum) + "' inline";
439
+            String arg = chanId + " 'set:hangup_after_bridge=false,set:record_concat_video=true,"
440
+                    +"bridge:{origination_caller_id_number=" + callerNum + "}" + getCallString(calleeNum) + "' inline";
413 441
             result = client.sendAsyncApiCommand(command, arg);
414 442
 
415 443
         } catch (Exception e) {

+ 6 - 7
midware-service/src/main/java/midware/service/init/WebSocketService.java

@@ -86,7 +86,6 @@ public class WebSocketService {
86 86
                 }
87 87
             }
88 88
 
89
-
90 89
             String param = "";
91 90
             boolean isSend = true;
92 91
             switch (type) {
@@ -359,9 +358,9 @@ public class WebSocketService {
359 358
                                     Channel tchan = EslCommon.getChanByExten(tAgent.getExten());
360 359
                                     if (tchan != null && StringHelper.isNotEmpty(tchan.getSessionId())) {
361 360
                                         agent.setOpType(4);
362
-                                        String rt = eslClientService.listen(agent.getExten(), tchan.getSessionId());
361
+                                        String rt = eslClientService.listen(agent.getExten(),tchan.getNumber(), tchan.getSessionId());
363 362
                                         if (StringHelper.isNotEmpty(rt)) {
364
-                                            EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + TargetAgentID);
363
+                                            EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + agent.getExten());
365 364
                                             isSend = false;
366 365
                                         }
367 366
                                     }
@@ -390,7 +389,7 @@ public class WebSocketService {
390 389
                                         String sid = tchan.getSessionId();
391 390
                                         String rt = eslClientService.insert(agent.getExten(), tchan.getNumber(), sid);
392 391
                                         if (StringHelper.isNotEmpty(rt)) {
393
-                                            EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + TargetAgentID);
392
+                                            EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + agent.getExten());
394 393
                                             isSend = false;
395 394
                                         }
396 395
                                     }
@@ -421,7 +420,7 @@ public class WebSocketService {
421 420
                                                 && !p.getChanId().equals(cid)).findFirst().get();
422 421
                                         String rt = eslClientService.intercept(agent.getExten(), tAgent.getExten(), channel.getChanId(), sid);
423 422
                                         if (StringHelper.isNotEmpty(rt)) {
424
-                                            EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + TargetAgentID);
423
+                                            EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + agent.getExten());
425 424
                                             isSend = false;
426 425
                                         }
427 426
                                     }
@@ -484,7 +483,7 @@ public class WebSocketService {
484 483
                                                     && !p.getChanId().equals(cid)).findFirst().get();
485 484
                                             String rt = eslClientService.intercept(agent.getExten(), tAgent.getExten(), channel.getChanId(), sid);
486 485
                                             if (StringHelper.isNotEmpty(rt)) {
487
-                                                EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + TargetAgentID);
486
+                                                EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + agent.getExten());
488 487
                                                 isSend = false;
489 488
                                             }
490 489
                                         }
@@ -508,7 +507,7 @@ public class WebSocketService {
508 507
                             } else {
509 508
                                 String rt = eslClientService.setWork(TargetAgentID, type.equals("ForceWorkOn"));
510 509
                                 if (StringHelper.isNotEmpty(rt)) {
511
-                                    EslCommon.sessionOpera.put(rt, type + "|" + TargetAgentID);
510
+                                    EslCommon.sessionOpera.put(rt, type + "|" + agentId + "|" + TargetAgentID);
512 511
                                     isSend = false;
513 512
                                 }
514 513
                             }

+ 68 - 225
midware-util/src/main/java/midware/util/helper/HttpHelper.java

@@ -1,16 +1,23 @@
1 1
 package midware.util.helper;
2 2
 
3
+import com.alibaba.fastjson2.JSON;
3 4
 import lombok.extern.slf4j.Slf4j;
5
+import org.apache.http.HttpEntity;
6
+import org.apache.http.HttpStatus;
7
+import org.apache.http.client.methods.CloseableHttpResponse;
8
+import org.apache.http.client.methods.HttpGet;
9
+import org.apache.http.client.methods.HttpPost;
10
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
11
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
12
+import org.apache.http.entity.StringEntity;
13
+import org.apache.http.impl.client.CloseableHttpClient;
14
+import org.apache.http.impl.client.HttpClients;
15
+import org.apache.http.ssl.SSLContextBuilder;
16
+import org.apache.http.util.EntityUtils;
4 17
 import org.springframework.stereotype.Component;
5 18
 
6
-import javax.net.ssl.*;
7
-import java.io.*;
8
-import java.net.ConnectException;
9
-import java.net.SocketTimeoutException;
10
-import java.net.URL;
11
-import java.net.URLConnection;
19
+import javax.net.ssl.SSLContext;
12 20
 import java.nio.charset.StandardCharsets;
13
-import java.security.cert.X509Certificate;
14 21
 
15 22
 @Component
16 23
 @Slf4j
@@ -21,238 +28,74 @@ public class HttpHelper {
21 28
      * @param url 发送请求的 URL
22 29
      * @return 所代表远程资源的响应结果
23 30
      */
24
-    public static String sendGet(String url)
25
-    {
26
-        return sendGet(url, "");
27
-    }
28
-
29
-    /**
30
-     * 向指定 URL 发送GET方法的请求
31
-     *
32
-     * @param url 发送请求的 URL
33
-     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
34
-     * @return 所代表远程资源的响应结果
35
-     */
36
-    public static String sendGet(String url, String param)
37
-    {
38
-        return sendGet(url, param, "UTF-8");
39
-    }
40
-
41
-    /**
42
-     * 向指定 URL 发送GET方法的请求
43
-     *
44
-     * @param url 发送请求的 URL
45
-     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
46
-     * @param contentType 编码类型
47
-     * @return 所代表远程资源的响应结果
48
-     */
49
-    public static String sendGet(String url, String param, String contentType)
50
-    {
51
-        StringBuilder result = new StringBuilder();
52
-        BufferedReader in = null;
53
-        try
54
-        {
55
-            String urlNameString = StringHelper.isEmpty(param) ? url + "?" + param : url;
56
-            log.info("sendGet - {}", urlNameString);
57
-            URL realUrl = new URL(urlNameString);
58
-            URLConnection connection = realUrl.openConnection();
59
-            connection.setRequestProperty("accept", "*/*");
60
-            connection.setRequestProperty("connection", "Keep-Alive");
61
-            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
62
-            connection.connect();
63
-            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
64
-            String line;
65
-            while ((line = in.readLine()) != null)
66
-            {
67
-                result.append(line);
68
-            }
69
-            log.info("recv - {}", result);
70
-        }
71
-        catch (ConnectException e)
72
-        {
73
-            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
74
-        }
75
-        catch (SocketTimeoutException e)
76
-        {
77
-            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
78
-        }
79
-        catch (IOException e)
80
-        {
81
-            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
82
-        }
83
-        catch (Exception e)
84
-        {
85
-            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
86
-        }
87
-        finally
88
-        {
89
-            try
90
-            {
91
-                if (in != null)
92
-                {
93
-                    in.close();
94
-                }
95
-            }
96
-            catch (Exception ex)
97
-            {
98
-                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
31
+    public static String get(String url) {
32
+        String result = "";
33
+        try {
34
+            // 创建httpclient对象
35
+            CloseableHttpClient httpClient = HttpClients.createDefault();
36
+            // 创建请求对象
37
+            HttpGet httpGet = new HttpGet(url);
38
+            // 发送请求,接收响应
39
+            CloseableHttpResponse response = httpClient.execute(httpGet);
40
+            // 获取状态码
41
+            int statusCode = response.getStatusLine().getStatusCode();
42
+            if (statusCode == HttpStatus.SC_OK) {
43
+                // 获取响应数据
44
+                HttpEntity entity = response.getEntity();
45
+                result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
99 46
             }
47
+            // 关闭资源
48
+            response.close();
49
+            httpClient.close();
50
+        } catch (Exception ex) {
51
+            log.error("get请求异常:" + url, ex);
100 52
         }
101
-        return result.toString();
53
+        return result;
102 54
     }
103 55
 
104 56
     /**
105 57
      * 向指定 URL 发送POST方法的请求
106 58
      *
107 59
      * @param url 发送请求的 URL
108
-     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
60
+     * @param param 请求参数json
109 61
      * @return 所代表远程资源的响应结果
110 62
      */
111
-    public static String sendPost(String url, String param)
112
-    {
113
-        PrintWriter out = null;
114
-        BufferedReader in = null;
115
-        StringBuilder result = new StringBuilder();
116
-        try
117
-        {
118
-            log.info("sendPost - {}", url);
119
-            URL realUrl = new URL(url);
120
-            URLConnection conn = realUrl.openConnection();
121
-            conn.setRequestProperty("accept", "*/*");
122
-            conn.setRequestProperty("connection", "Keep-Alive");
123
-            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
124
-            conn.setRequestProperty("Accept-Charset", "utf-8");
125
-            conn.setRequestProperty("contentType", "utf-8");
126
-            conn.setDoOutput(true);
127
-            conn.setDoInput(true);
128
-            out = new PrintWriter(conn.getOutputStream());
129
-            out.print(param);
130
-            out.flush();
131
-            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
132
-            String line;
133
-            while ((line = in.readLine()) != null)
134
-            {
135
-                result.append(line);
136
-            }
137
-            log.info("recv - {}", result);
138
-        }
139
-        catch (ConnectException e)
140
-        {
141
-            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
142
-        }
143
-        catch (SocketTimeoutException e)
144
-        {
145
-            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
146
-        }
147
-        catch (IOException e)
148
-        {
149
-            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
150
-        }
151
-        catch (Exception e)
152
-        {
153
-            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
154
-        }
155
-        finally
156
-        {
157
-            try
158
-            {
159
-                if (out != null)
160
-                {
161
-                    out.close();
162
-                }
163
-                if (in != null)
164
-                {
165
-                    in.close();
166
-                }
167
-            }
168
-            catch (IOException ex)
169
-            {
170
-                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
171
-            }
172
-        }
173
-        return result.toString();
174
-    }
63
+    public static String post(String url, String param) {
64
+        String result = "";
65
+        try {
66
+            // 创建httpclient对象
67
+            CloseableHttpClient httpClient = HttpClients.createDefault();
68
+            if(url.startsWith("https")) {
69
+                SSLContext sslContext = new SSLContextBuilder()
70
+                        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
71
+                        .build();
175 72
 
176
-    public static String sendSSLPost(String url, String param)
177
-    {
178
-        StringBuilder result = new StringBuilder();
179
-        String urlNameString = url + "?" + param;
180
-        try
181
-        {
182
-            log.info("sendSSLPost - {}", urlNameString);
183
-            SSLContext sc = SSLContext.getInstance("SSL");
184
-            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
185
-            URL console = new URL(urlNameString);
186
-            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
187
-            conn.setRequestProperty("accept", "*/*");
188
-            conn.setRequestProperty("connection", "Keep-Alive");
189
-            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
190
-            conn.setRequestProperty("Accept-Charset", "utf-8");
191
-            conn.setRequestProperty("contentType", "utf-8");
192
-            conn.setDoOutput(true);
193
-            conn.setDoInput(true);
194
-
195
-            conn.setSSLSocketFactory(sc.getSocketFactory());
196
-            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
197
-            conn.connect();
198
-            InputStream is = conn.getInputStream();
199
-            BufferedReader br = new BufferedReader(new InputStreamReader(is));
200
-            String ret = "";
201
-            while ((ret = br.readLine()) != null)
202
-            {
203
-                if (ret != null && !"".equals(ret.trim()))
204
-                {
205
-                    result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
206
-                }
73
+                httpClient = HttpClients.custom()
74
+                        .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
75
+                        .setSSLContext(sslContext)
76
+                        .build();
207 77
             }
208
-            log.info("recv - {}", result);
209
-            conn.disconnect();
210
-            br.close();
211
-        }
212
-        catch (ConnectException e)
213
-        {
214
-            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
215
-        }
216
-        catch (SocketTimeoutException e)
217
-        {
218
-            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
219
-        }
220
-        catch (IOException e)
221
-        {
222
-            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
223
-        }
224
-        catch (Exception e)
225
-        {
226
-            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
227
-        }
228
-        return result.toString();
229
-    }
230 78
 
231
-    private static class TrustAnyTrustManager implements X509TrustManager
232
-    {
233
-        @Override
234
-        public void checkClientTrusted(X509Certificate[] chain, String authType)
235
-        {
236
-        }
79
+            // 创建请求对象
80
+            HttpPost httpPost = new HttpPost(url);
81
+            httpPost.setEntity(new StringEntity(param,StandardCharsets.UTF_8));
82
+            httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
237 83
 
238
-        @Override
239
-        public void checkServerTrusted(X509Certificate[] chain, String authType)
240
-        {
241
-        }
242
-
243
-        @Override
244
-        public X509Certificate[] getAcceptedIssuers()
245
-        {
246
-            return new X509Certificate[] {};
247
-        }
248
-    }
249
-
250
-    private static class TrustAnyHostnameVerifier implements HostnameVerifier
251
-    {
252
-        @Override
253
-        public boolean verify(String hostname, SSLSession session)
254
-        {
255
-            return true;
84
+            // 发送请求,接收响应
85
+            CloseableHttpResponse response = httpClient.execute(httpPost);
86
+            // 获取状态码
87
+            int statusCode = response.getStatusLine().getStatusCode();
88
+            if (statusCode == HttpStatus.SC_OK) {
89
+                // 获取响应数据
90
+                HttpEntity entity1 = response.getEntity();
91
+                result = EntityUtils.toString(entity1,StandardCharsets.UTF_8);
92
+            }
93
+            // 关闭资源
94
+            response.close();
95
+            httpClient.close();
96
+        } catch (Exception ex) {
97
+            log.error("post请求异常:" + url + (StringHelper.isNotEmpty(param) ? "|" + param : ""), ex);
256 98
         }
99
+        return result;
257 100
     }
258 101
 }

+ 50 - 21
midware-util/src/main/java/midware/util/helper/TtsHelper.java

@@ -1,11 +1,58 @@
1 1
 package midware.util.helper;
2 2
 
3
+import com.alibaba.fastjson2.JSON;
4
+import lombok.extern.slf4j.Slf4j;
5
+
3 6
 import java.io.File;
7
+import java.io.FileOutputStream;
4 8
 import java.io.IOException;
5 9
 import java.text.SimpleDateFormat;
10
+import java.util.Base64;
6 11
 import java.util.Date;
12
+import java.util.HashMap;
13
+import java.util.Map;
7 14
 
15
+@Slf4j
8 16
 public class TtsHelper {
17
+
18
+    private static String ttstype="modelscope";//ekho
19
+
20
+    private static void transfer(String word, String filePath){
21
+        switch (ttstype){
22
+            case "ekho":
23
+                try {
24
+                    String command = "ekho " + word + " -o " + filePath;
25
+                    Process process = Runtime.getRuntime().exec(command);
26
+                    process.waitFor();
27
+                } catch (IOException | InterruptedException ex) {
28
+                    log.error("ekho异常", ex);
29
+                }
30
+                break;
31
+            case "modelscope":
32
+                Map<String,Object> param=new HashMap<>();
33
+                param.put("input",word);
34
+                Map<String,Object> param1=new HashMap<>();
35
+                param1.put("voice","zhitian_emo");
36
+                param.put("parameters",param1);
37
+                System.out.println(JSON.toJSONString(param));
38
+                String result=HttpHelper.post("http://192.168.1.17:8000/call", JSON.toJSONString(param));
39
+                if(StringHelper.isNotEmpty(result)) {
40
+                    try {
41
+                        Map map=JSON.parseObject(result,Map.class);
42
+                        System.out.println(map.get("output_wav").toString());
43
+                        byte[] bytes = Base64.getDecoder().decode(map.get("output_wav").toString());
44
+                        File file = new File(filePath);
45
+                        FileOutputStream outputStream=new FileOutputStream(file);
46
+                        outputStream.write(bytes);
47
+                        outputStream.close();
48
+                    }catch (Exception ex){
49
+                        log.error("modelscope异常", ex);
50
+                    }
51
+                }
52
+                break;
53
+        }
54
+    }
55
+
9 56
     public static String TextToSpeech(String word) {
10 57
         return TextToSpeech(word, "");
11 58
     }
@@ -22,13 +69,7 @@ public class TtsHelper {
22 69
         }
23 70
         String filePath = file.getAbsolutePath() + "/" + filename + ".wav";
24 71
 
25
-        try {
26
-            String command = "ekho " + word + " -o " + filePath;
27
-            Process process = Runtime.getRuntime().exec(command);
28
-            process.waitFor();
29
-        } catch (IOException | InterruptedException e) {
30
-            throw new RuntimeException(e);
31
-        }
72
+        transfer(word,filePath);
32 73
 
33 74
         return filePath;
34 75
     }
@@ -43,13 +84,7 @@ public class TtsHelper {
43 84
         String filePath = file.getAbsolutePath() + "/" + filename + ".wav";
44 85
 
45 86
         if (!new File(filePath).exists()) {
46
-            try {
47
-                String command = "ekho " + word + " -o " + filePath;
48
-                Process process = Runtime.getRuntime().exec(command);
49
-                process.waitFor();
50
-            } catch (IOException | InterruptedException e) {
51
-                throw new RuntimeException(e);
52
-            }
87
+            transfer(word,filePath);
53 88
         }
54 89
         return filePath;
55 90
     }
@@ -64,13 +99,7 @@ public class TtsHelper {
64 99
         String filePath = file.getAbsolutePath() + "/" + filename + ".wav";
65 100
 
66 101
         if (!new File(filePath).exists()) {
67
-            try {
68
-                String command = "ekho " + word + " -o " + filePath;
69
-                Process process = Runtime.getRuntime().exec(command);
70
-                process.waitFor();
71
-            } catch (IOException | InterruptedException e) {
72
-                throw new RuntimeException(e);
73
-            }
102
+            transfer(word,filePath);
74 103
         }
75 104
         return filePath;
76 105
     }