xiongzhu пре 3 година
родитељ
комит
9673c877c8

+ 95 - 75
src/main/java/com/izouma/yags/camp/api/CampApiService.java

@@ -3,7 +3,9 @@ package com.izouma.yags.camp.api;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.JSONObject;
 import com.izouma.yags.domain.CampToken;
 import com.izouma.yags.domain.CampToken;
+import com.izouma.yags.dto.JsonBody;
 import com.izouma.yags.exception.BusinessException;
 import com.izouma.yags.exception.BusinessException;
+import com.izouma.yags.repo.CampTokenRepo;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import okhttp3.*;
 import okhttp3.*;
 import okhttp3.logging.HttpLoggingInterceptor;
 import okhttp3.logging.HttpLoggingInterceptor;
@@ -16,7 +18,12 @@ import java.util.List;
 @Slf4j
 @Slf4j
 public class CampApiService {
 public class CampApiService {
 
 
-    private volatile OkHttpClient client;
+    private volatile OkHttpClient  client;
+    private final    CampTokenRepo campTokenRepo;
+
+    public CampApiService(CampTokenRepo campTokenRepo) {
+        this.campTokenRepo = campTokenRepo;
+    }
 
 
     private OkHttpClient getClient() {
     private OkHttpClient getClient() {
         if (client == null) {
         if (client == null) {
@@ -31,104 +38,117 @@ public class CampApiService {
         return client;
         return client;
     }
     }
 
 
-    private CampToken getCampToken() {
-        CampToken campToken = new CampToken();
-        campToken.setUserId("436174868");
-        campToken.setToken("YWUU7xKq");
-        return campToken;
+    private ApiResponse request(String url, RequestBody requestBody) {
+        ApiResponse apiResponse = null;
+        for (CampToken token : campTokenRepo.findAll()) {
+            if (requestBody instanceof FormBody) {
+                FormBody formBody = (FormBody) requestBody;
+                FormBody.Builder builder = new FormBody.Builder();
+                for (int i = 0; i < formBody.size(); i++) {
+                    builder.add(formBody.name(i), formBody.value(i));
+                }
+                builder.add("token", token.getToken());
+                builder.add("userId", token.getUserId());
+                requestBody = builder.build();
+            } else if (requestBody instanceof MultipartBody) {
+                MultipartBody multipartBody = (MultipartBody) requestBody;
+                MultipartBody.Builder builder = new MultipartBody.Builder();
+                for (int i = 0; i < multipartBody.size(); i++) {
+                    builder.addPart(multipartBody.part(i));
+                }
+                builder.addFormDataPart("token", token.getToken());
+                builder.addFormDataPart("userId", token.getUserId());
+                requestBody = builder.build();
+            } else if (requestBody instanceof JsonBody) {
+                JsonBody jsonBody = (JsonBody) requestBody;
+                JSONObject jsonObject = jsonBody.getJson();
+                jsonObject.put("token", token.getToken());
+                jsonObject.put("userId", token.getUserId());
+                requestBody = new JsonBody(jsonObject);
+            }
+            Request request = new Request.Builder()
+                    .addHeader("userId", token.getUserId())
+                    .addHeader("token", token.getToken())
+                    .url(url)
+                    .post(requestBody)
+                    .build();
+
+            try {
+                Response response = getClient().newCall(request).execute();
+                if (response.isSuccessful() && response.body() != null) {
+                    ApiResponse res = JSON.parseObject(response.body().string(), ApiResponse.class);
+                    if (res.getReturnCode() == 0) {
+                        apiResponse = res;
+                        break;
+                    }
+                }
+                response.close();
+            } catch (IOException e) {
+                log.error("请求失败", e);
+            }
+        }
+        return apiResponse;
     }
     }
 
 
-    public List<RongYaoRole> getRoleItems(String userId) throws IOException {
-        OkHttpClient client = new OkHttpClient();
-        CampToken token = getCampToken();
+    public List<RongYaoRole> getRoleItems(String userId) {
         RequestBody formBody = new FormBody.Builder()
         RequestBody formBody = new FormBody.Builder()
                 .add("friendUserId", userId)
                 .add("friendUserId", userId)
                 .add("gameId", "20001")
                 .add("gameId", "20001")
-                .add("token", token.getToken())
-                .add("userId", token.getUserId())
                 .build();
                 .build();
-        Request request = new Request.Builder()
-                .addHeader("userId", token.getUserId())
-                .addHeader("token", token.getToken())
-                .url("https://ssl.kohsocialapp.qq.com:10001/game/battleprofile")
-                .post(formBody)
-                .build();
-        try (Response response = getClient().newCall(request).execute()) {
-            ResponseBody responseBody = response.body();
-            if (responseBody != null) {
-                String body = responseBody.string();
-                ApiResponse res = JSON.parseObject(body, ApiResponse.class);
-                if (res.getReturnCode() == 0) {
-                    QueryRole data = ((JSONObject) res.getData()).toJavaObject(QueryRole.class);
-                    return data.getRolelist();
-                } else {
-                    log.error("获取角色列表失败, returnCode={}, msg={}", res.getReturnCode(), res.getReturnMsg());
-                    throw new BusinessException("查询游戏角色失败");
-                }
+        ApiResponse res = request("https://ssl.kohsocialapp.qq.com:10001/game/battleprofile", formBody);
+        try {
+            if (res.getReturnCode() == 0) {
+                QueryRole data = ((JSONObject) res.getData()).toJavaObject(QueryRole.class);
+                return data.getRolelist();
+            } else {
+                log.error("获取角色列表失败, returnCode={}, msg={}", res.getReturnCode(), res.getReturnMsg());
+                throw new BusinessException("查询游戏角色失败");
             }
             }
+        } catch (Exception e) {
+            log.error("获取角色列表失败", e);
+            throw new BusinessException("查询游戏角色失败");
         }
         }
-        throw new BusinessException("查询游戏角色失败");
     }
     }
 
 
-    public QueryBattle queryBattle(String roleId) throws IOException {
-        CampToken token = getCampToken();
-        JSONObject content = new JSONObject();
-        content.put("friendRoleId", roleId);
-        content.put("userId", token.getUserId());
-        Request request = new Request.Builder()
-                .addHeader("userId", token.getUserId())
-                .addHeader("token", token.getToken())
-                .url("https://kohcamp.qq.com/game/morebattlelist")
-                .post(RequestBody.create(MediaType.parse("application/json"), content.toJSONString()))
+    public QueryBattle queryBattle(String roleId) {
+        JsonBody jsonBody = new JsonBody.Builder()
+                .add("friendRoleId", roleId)
                 .build();
                 .build();
-        try (Response response = getClient().newCall(request).execute()) {
-            ResponseBody responseBody = response.body();
-            if (responseBody != null) {
-                String body = responseBody.string();
-                ApiResponse res = JSON.parseObject(body, ApiResponse.class);
-                if (res.getReturnCode() == 0) {
-                    QueryBattle data = ((JSONObject) res.getData()).toJavaObject(QueryBattle.class);
-                    return data;
-                } else {
-                    log.error("查询对战信息失败, returnCode={}, msg={}", res.getReturnCode(), res.getReturnMsg());
-                    throw new BusinessException("查询对战信息失败");
-                }
+        try {
+            ApiResponse res = request("https://kohcamp.qq.com/game/morebattlelist", jsonBody);
+            if (res.getReturnCode() == 0) {
+                QueryBattle data = ((JSONObject) res.getData()).toJavaObject(QueryBattle.class);
+                return data;
+            } else {
+                log.error("查询对战信息失败, returnCode={}, msg={}", res.getReturnCode(), res.getReturnMsg());
+                throw new BusinessException("查询对战信息失败");
             }
             }
+        } catch (Exception e) {
+            log.error("查询对战信息失败", e);
+            throw new BusinessException("查询对战信息失败");
         }
         }
-        throw new BusinessException("查询对战信息失败");
     }
     }
 
 
     public QueryBattleDetail queryBattleDetail(String gameSeq, String gameSvrId, Integer pvpType, String toAppRoleId, String relaySvrId) throws IOException {
     public QueryBattleDetail queryBattleDetail(String gameSeq, String gameSvrId, Integer pvpType, String toAppRoleId, String relaySvrId) throws IOException {
-        CampToken token = getCampToken();
         RequestBody content = new FormBody.Builder()
         RequestBody content = new FormBody.Builder()
                 .add("gameSeq", gameSeq)
                 .add("gameSeq", gameSeq)
                 .add("gameSvrId", gameSvrId)
                 .add("gameSvrId", gameSvrId)
                 .add("pvpType", pvpType.toString())
                 .add("pvpType", pvpType.toString())
                 .add("toAppRoleId", toAppRoleId)
                 .add("toAppRoleId", toAppRoleId)
                 .add("relaySvrId", relaySvrId)
                 .add("relaySvrId", relaySvrId)
-                .add("userId", token.getUserId())
-                .add("token", token.getToken())
-                .build();
-        Request request = new Request.Builder()
-                .addHeader("userId", token.getUserId())
-                .addHeader("token", token.getToken())
-                .url("https://ssl.kohsocialapp.qq.com:10001/role/h5getplaydetail")
-                .post(content)
                 .build();
                 .build();
-        try (Response response = getClient().newCall(request).execute()) {
-            ResponseBody responseBody = response.body();
-            if (responseBody != null) {
-                String body = responseBody.string();
-                ApiResponse res = JSON.parseObject(body, ApiResponse.class);
-                if (res.getReturnCode() == 0) {
-                    QueryBattleDetail data = ((JSONObject) res.getData()).toJavaObject(QueryBattleDetail.class);
-                    return data;
-                } else {
-                    log.error("查询对战信息失败, returnCode={}, msg={}", res.getReturnCode(), res.getReturnMsg());
-                    throw new BusinessException("查询对战信息失败");
-                }
+        try {
+            ApiResponse res = request("https://ssl.kohsocialapp.qq.com:10001/role/h5getplaydetail", content);
+            if (res.getReturnCode() == 0) {
+                QueryBattleDetail data = ((JSONObject) res.getData()).toJavaObject(QueryBattleDetail.class);
+                return data;
+            } else {
+                log.error("查询对战信息失败, returnCode={}, msg={}", res.getReturnCode(), res.getReturnMsg());
+                throw new BusinessException("查询对战信息失败");
             }
             }
+        } catch (Exception e) {
+            log.error("查询对战信息失败", e);
+            throw new BusinessException("查询对战信息失败");
         }
         }
-        throw new BusinessException("查询对战信息失败");
     }
     }
 }
 }

+ 56 - 0
src/main/java/com/izouma/yags/dto/JsonBody.java

@@ -0,0 +1,56 @@
+package com.izouma.yags.dto;
+
+import com.alibaba.fastjson.JSONObject;
+import okhttp3.MediaType;
+import okhttp3.RequestBody;
+import okio.BufferedSink;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+
+public class JsonBody extends RequestBody {
+
+    private final JSONObject json;
+
+    public JsonBody(JSONObject json) {
+        this.json = json;
+    }
+
+    public JSONObject getJson() {
+        return json;
+    }
+
+    @Nullable
+    @Override
+    public MediaType contentType() {
+        return MediaType.parse("application/json; charset=utf-8");
+    }
+
+    @Override
+    public long contentLength() throws IOException {
+        return json.toJSONString().length();
+    }
+
+    @Override
+    public void writeTo(BufferedSink bufferedSink) throws IOException {
+        bufferedSink.write(json.toJSONString().getBytes());
+    }
+
+    public static class Builder {
+
+        private final JSONObject jsonObject;
+
+        public Builder() {
+            jsonObject = new JSONObject();
+        }
+
+        public Builder add(String key, Object value) {
+            jsonObject.put(key, value);
+            return this;
+        }
+
+        public JsonBody build() {
+            return new JsonBody(jsonObject);
+        }
+    }
+}

+ 1 - 0
src/main/java/com/izouma/yags/security/WebSecurityConfig.java

@@ -83,6 +83,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                 .antMatchers("/room/roomList").permitAll()
                 .antMatchers("/room/roomList").permitAll()
                 .antMatchers("/notify/alipay").permitAll()
                 .antMatchers("/notify/alipay").permitAll()
                 .antMatchers("/order/pay/form/**").permitAll()
                 .antMatchers("/order/pay/form/**").permitAll()
+                .antMatchers("/bindGame/saveToken").permitAll()
                 // all other requests need to be authenticated
                 // all other requests need to be authenticated
                 .anyRequest().authenticated().and()
                 .anyRequest().authenticated().and()
                 // make sure we use stateless session; session won't be used to
                 // make sure we use stateless session; session won't be used to

+ 8 - 0
src/main/java/com/izouma/yags/web/BindGameController.java

@@ -1,7 +1,9 @@
 package com.izouma.yags.web;
 package com.izouma.yags.web;
 
 
 import com.izouma.yags.domain.BindGame;
 import com.izouma.yags.domain.BindGame;
+import com.izouma.yags.domain.CampToken;
 import com.izouma.yags.dto.PageQuery;
 import com.izouma.yags.dto.PageQuery;
+import com.izouma.yags.repo.CampTokenRepo;
 import com.izouma.yags.service.BindGameService;
 import com.izouma.yags.service.BindGameService;
 import com.izouma.yags.utils.SecurityUtils;
 import com.izouma.yags.utils.SecurityUtils;
 import lombok.AllArgsConstructor;
 import lombok.AllArgsConstructor;
@@ -17,6 +19,12 @@ import java.util.List;
 @AllArgsConstructor
 @AllArgsConstructor
 public class BindGameController extends BaseController {
 public class BindGameController extends BaseController {
     private BindGameService bindGameService;
     private BindGameService bindGameService;
+    private CampTokenRepo   campTokenRepo;
+
+    @PostMapping("/saveToken")
+    public void saveToken(@RequestParam String userId, @RequestParam String token) {
+        campTokenRepo.save(new CampToken(userId, token));
+    }
 
 
     @PostMapping("/all")
     @PostMapping("/all")
     @PreAuthorize("hasRole('ADMIN')")
     @PreAuthorize("hasRole('ADMIN')")

+ 7 - 3
src/test/java/com/izouma/yags/camp/api/CampApiServiceTest.java

@@ -2,14 +2,18 @@ package com.izouma.yags.camp.api;
 
 
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
 
 
 import java.io.IOException;
 import java.io.IOException;
 import java.util.List;
 import java.util.List;
 import java.util.stream.Collectors;
 import java.util.stream.Collectors;
 
 
 @Slf4j
 @Slf4j
+@SpringBootTest
 class CampApiServiceTest {
 class CampApiServiceTest {
-    private CampApiService campApiService = new CampApiService();
+    @Autowired
+    private CampApiService campApiService;
 
 
     @Test
     @Test
     public void getRoleItems() throws IOException {
     public void getRoleItems() throws IOException {
@@ -21,9 +25,9 @@ class CampApiServiceTest {
 
 
     @Test
     @Test
     public void queryBattle() throws IOException {
     public void queryBattle() throws IOException {
-        QueryBattle queryBattle1 = campApiService.queryBattle("1869802843");
+        QueryBattle queryBattle1 = campApiService.queryBattle("1667628341");
         System.out.println(queryBattle1.getInvisible() + queryBattle1.getInvisDes());
         System.out.println(queryBattle1.getInvisible() + queryBattle1.getInvisDes());
-        QueryBattle queryBattle2 = campApiService.queryBattle("1501416972");
+        QueryBattle queryBattle2 = campApiService.queryBattle("3517240704");
         System.out.println(queryBattle2.getInvisible() + queryBattle2.getInvisDes());
         System.out.println(queryBattle2.getInvisible() + queryBattle2.getInvisDes());
 
 
         Battle battle = queryBattle2.getList().get(5);
         Battle battle = queryBattle2.getList().get(5);