From fec901970a61ab6610af4dd57d3fa103b7d7e419 Mon Sep 17 00:00:00 2001 From: Yutousama <583819556@qq.com> Date: Thu, 5 Jan 2023 14:36:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9EB=E7=AB=99=E7=9B=B4=E6=92=AD?= =?UTF-8?q?=E9=97=B4=E9=A2=86=E7=94=B5=E6=B1=A0=E5=8A=9F=E8=83=BD=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9EB=E7=AB=99APP=E6=93=8D=E4=BD=9C=E7=9B=B8?= =?UTF-8?q?=E5=85=B3API=20=E4=BC=98=E5=8C=96B=E7=AB=99=E7=99=BB=E9=99=86?= =?UTF-8?q?=E6=A0=B9=E6=8D=AEQQ=E5=8F=B7=E5=88=86=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E5=AD=98=E5=82=A8=20=E4=BF=AE=E5=A4=8DRedis=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E6=97=B6=E4=B8=BA=E7=A9=BA=E6=8A=A5=E9=94=99?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 23 ++- .../qqbot/Controllers/BiliBiliController.java | 3 +- .../com/yutou/qqbot/QQBotApplication.java | 2 +- .../java/com/yutou/qqbot/QQBotManager.java | 1 + .../com/yutou/qqbot/bilibili/AppUserTask.java | 76 ++++++++++ .../qqbot/bilibili/BiliBiliAppUtils.java | 141 ++++++++++++++++++ .../yutou/qqbot/bilibili/BiliBiliManga.java | 43 +++--- .../yutou/qqbot/bilibili/BiliBiliUtils.java | 97 +++++++----- .../com/yutou/qqbot/bilibili/BiliLogin.java | 83 +++++++---- .../qqbot/models/BiliBili/BiliBiliLive.java | 61 +++++--- .../qqbot/models/BiliBili/BiliVideo.java | 31 ++-- .../java/com/yutou/qqbot/models/Model.java | 23 +-- .../models/WebSign/BiliBiliMangeSign.java | 6 +- .../java/com/yutou/qqbot/utlis/RSAUtils.java | 136 +++++++++++++++++ .../com/yutou/qqbot/utlis/RedisTools.java | 42 ++++-- 15 files changed, 611 insertions(+), 157 deletions(-) create mode 100644 src/main/java/com/yutou/qqbot/bilibili/AppUserTask.java create mode 100644 src/main/java/com/yutou/qqbot/bilibili/BiliBiliAppUtils.java create mode 100644 src/main/java/com/yutou/qqbot/utlis/RSAUtils.java diff --git a/pom.xml b/pom.xml index 4e3739c..7dcee9d 100644 --- a/pom.xml +++ b/pom.xml @@ -52,7 +52,7 @@ redis.clients jedis - 4.2.3 + 4.3.1 @@ -60,7 +60,7 @@ com.alibaba.fastjson2 fastjson2 - 2.0.14 + 2.0.22 @@ -81,24 +81,24 @@ org.seleniumhq.selenium selenium-java - 4.5.0 + 4.7.1 org.seleniumhq.selenium selenium-chrome-driver - 4.5.0 + 4.7.1 org.seleniumhq.selenium selenium-api - 4.5.0 + 4.7.1 org.seleniumhq.selenium selenium-remote-driver - 4.5.0 + 4.7.1 @@ -117,13 +117,13 @@ com.google.zxing core - 3.5.0 + 3.5.1 com.google.protobuf protobuf-java - 3.21.1 + 3.21.12 com.google.protobuf @@ -138,6 +138,13 @@ 0.10.2 + + + org.brotli + dec + 0.1.2 + + diff --git a/src/main/java/com/yutou/qqbot/Controllers/BiliBiliController.java b/src/main/java/com/yutou/qqbot/Controllers/BiliBiliController.java index 2cad996..ba003ab 100644 --- a/src/main/java/com/yutou/qqbot/Controllers/BiliBiliController.java +++ b/src/main/java/com/yutou/qqbot/Controllers/BiliBiliController.java @@ -1,6 +1,7 @@ package com.yutou.qqbot.Controllers; import com.alibaba.fastjson2.JSONObject; +import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.BiliBili.BiliVideo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -17,7 +18,7 @@ public class BiliBiliController { String url = json.getString("url"); boolean downDanmu = json.containsKey("danmu") && "on".equals(json.getString("danmu")); boolean merge = json.containsKey("merge") && "on".equals(json.getString("merge")); - BiliVideo video = new BiliVideo(); + BiliVideo video = new BiliVideo(QQBotManager.defQQ); video.downVideo(url, downDanmu, merge); } ).start(); diff --git a/src/main/java/com/yutou/qqbot/QQBotApplication.java b/src/main/java/com/yutou/qqbot/QQBotApplication.java index c5f1c65..a2e6f89 100644 --- a/src/main/java/com/yutou/qqbot/QQBotApplication.java +++ b/src/main/java/com/yutou/qqbot/QQBotApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class QQBotApplication { - public static final String version="QQBot v.1.3.6"; + public static final String version="QQBot v.1.4b"; public static void main(String[] args) { System.out.println("version = " + version); SpringApplication.run(QQBotApplication.class, args); diff --git a/src/main/java/com/yutou/qqbot/QQBotManager.java b/src/main/java/com/yutou/qqbot/QQBotManager.java index 468d2e3..b70931b 100644 --- a/src/main/java/com/yutou/qqbot/QQBotManager.java +++ b/src/main/java/com/yutou/qqbot/QQBotManager.java @@ -21,6 +21,7 @@ import java.util.Objects; public class QQBotManager { public static Long defGroup = 891655174L; + public static Long defQQ = 583819556L; private static QQBotManager botManager = null; diff --git a/src/main/java/com/yutou/qqbot/bilibili/AppUserTask.java b/src/main/java/com/yutou/qqbot/bilibili/AppUserTask.java new file mode 100644 index 0000000..8f8217a --- /dev/null +++ b/src/main/java/com/yutou/qqbot/bilibili/AppUserTask.java @@ -0,0 +1,76 @@ +package com.yutou.qqbot.bilibili; + + +import lombok.Data; + +import java.util.List; + +@Data +public class AppUserTask { + private long isSurplus; + private long status; + private long progress; + private long target; + private Wallet wallet; + private List weekTask; + private long weekTotal; + private long weekGroup; + private DayTask dayTask; + + + public String toMessageFormat() { + StringBuilder sb = new StringBuilder(); + sb.append("当前电池数量:").append(String.format("%.2f", (double) wallet.gold / 100)).append("\n"); + sb.append("当前银瓜子数量:").append(wallet.silver).append("\n"); + sb.append("每日领取电池:").append(dayTask.toMessageFormat()).append("\n"); + weekTask.forEach(task -> sb.append(task.toMessageFormat(weekTotal)).append("\n")); + return sb.toString(); + } + + @Data + public static class DayTask { + private int status; + private long progress; + private long target; + + public String toMessageFormat() { + return switch (getStatus()) { + case 0 -> "不可领取,需要发送弹幕:" + getTarget() + ",进度:" + getProgress(); + case 2 -> "未领取"; + case 3 -> "已领取"; + default -> "未知状态:" + this; + }; + } + + } + + @Data + public static class Wallet { + private long gold; + private long silver; + } + +// WeekTask.java + + + @Data + public static class WeekTask { + private long rewardNum; + private long minimalDay; + private int status; + private int id; + + public String toMessageFormat(long totalNum) { + return switch (getStatus()) { + case 0 -> + "任务id:" + id + ",不可领取, 进度天数:" + totalNum + ",需要天数:" + minimalDay + ",任务奖励电池:" + rewardNum; + case 2 -> "任务id:" + id + ":未领取" + ",任务奖励电池:" + rewardNum; + case 3 -> "任务id:" + id + ":已领取" + ",任务奖励电池:" + rewardNum; + default -> "未知状态:" + this; + }; + } + } + +} + + diff --git a/src/main/java/com/yutou/qqbot/bilibili/BiliBiliAppUtils.java b/src/main/java/com/yutou/qqbot/bilibili/BiliBiliAppUtils.java new file mode 100644 index 0000000..0070530 --- /dev/null +++ b/src/main/java/com/yutou/qqbot/bilibili/BiliBiliAppUtils.java @@ -0,0 +1,141 @@ +package com.yutou.qqbot.bilibili; + +import com.alibaba.fastjson2.JSONObject; +import com.yutou.qqbot.QQBotManager; +import com.yutou.qqbot.utlis.AppTools; +import com.yutou.qqbot.utlis.HttpTools; + +import javax.net.ssl.HttpsURLConnection; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +public class BiliBiliAppUtils { + private static final String AppKey = "1d8b6e7d45233436"; + private static final String AppSec = "560c52ccd288fed045859ed18bffd973"; + + private BiliBiliUtils biliUtils; + + public BiliBiliAppUtils(Long qq) { + biliUtils = BiliBiliUtils.getInstance(qq); + } + + public String getAccessToken() { + try { + String tmpUrl = "https://www.mcbbs.net/template/mcbbs/image/special_photo_bg.png"; + String sign = AppTools.getMD5("api=" + tmpUrl + AppSec); + JSONObject get = biliUtils.http_get(" https://passport.bilibili.com/login/app/third?appkey=" + AppKey + "&api=" + tmpUrl + "&sign=" + sign); + assert get != null; + String uri = get.getJSONObject("data").getString("confirm_uri"); + HttpsURLConnection connection = biliUtils.getBiliHttpGet(uri, biliUtils.getCookie()); + connection.connect(); + if (connection.getResponseCode() == 200) { + Map params = HttpTools.getUrlParams(connection.getURL().toString()); + return params.get("access_key"); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + private Map sign(Map map) { + map.putAll(getDefaultHeader()); + map = sort(map); + StringBuilder builder = new StringBuilder(); + for (String key : map.keySet()) { + builder.append(key).append("=").append(map.get(key)).append("&"); + } + String param = builder.substring(0, builder.length() - 1); + map.put("sign", AppTools.getMD5(param + AppSec)); + return map; + } + + private Map getDefaultHeader() { + Map map = new TreeMap<>(); + map.put("access_key", getAccessToken()); + map.put("actionKey", "appkey"); + map.put("appkey", AppKey); + map.put("build", "7120200"); + map.put("c_locale", "zh_CN"); + map.put("channel", "xiaomi_cn_tv.danmaku.bili_20210930"); + map.put("device", "android"); + map.put("disable_rcmd", "0"); + map.put("mobi_app", "android"); + map.put("platform", "android"); + map.put("s_locale", "zh_CN"); + map.put("statistics", URLEncoder.encode("{\"appId\":1,\"platform\":3,\"version\":\"7.12.0\",\"abtest\":\"\"}", Charset.defaultCharset())); + map.put("ts", (System.currentTimeMillis() / 1000) + ""); + return map; + } + + private LinkedHashMap sort(Map map) { + return new LinkedHashMap<>(new TreeMap<>(map)); + } + + private Map getHeaderMap() { + String md5_1 = AppTools.getMD5(System.currentTimeMillis() + ""); + String md5_2 = AppTools.getMD5(System.currentTimeMillis() + ""); + String trace_id = md5_1 + ":" + md5_2.substring(0, 16) + ":0:0"; + Map map = new TreeMap<>(); + map.put("x-bili-mid", "96300"); + map.put("x-bili-trace-id", trace_id); + map.put("x-bili-aurora-zone", ""); + map.put("x-bili-aurora-eid", "WFICRlE="); + map.put("APP-KEY", "android64"); + map.put("bili-http-engine", "cronet"); + map.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); + map.put("session_id", md5_1.substring(0, 8)); + map.put("Host", "api.live.bilibili.com"); + map.put("Connection", "keep-alive"); + map.put("fp_local", md5_1 + md5_2); + map.put("fp_remote", md5_1 + md5_2); + map.put("env", "prod"); + map.put("buvid", "XUF43FCF17D1747514C79C6D3D43B64C8D1B2"); + map.put("Accept-Encoding", "gzip, deflate, br"); + map.put("User-Agent", "Mozilla/5.0 BiliDroid/7.4.0 (bbcallen@gmail.com) os/android model/22061218C mobi_app/android build/7040300 channel/xiaomi_cn_tv.danmaku.bili_20210930 innerVer/7040310 osVer/12 network/2"); + return map; + } + + public AppUserTask getTaskProgress() { + JSONObject task = biliUtils.http_get("https://api.live.bilibili.com/xlive/app-ucenter/v1/userTask/GetUserTaskProgress"); + assert task != null; + return task.getObject("data", AppUserTask.class); + } + + private void setUserTaskProgress(int index) { + Map map = new TreeMap<>(); + map.put("target_id", "33989"); + map.put("reward_index", index + ""); + + JSONObject httpGet = biliUtils.http( + "https://api.live.bilibili.com/xlive/app-ucenter/v1/userTask/UserTaskReceiveRewards", + BiliBiliUtils.HTTP.POST, + HttpTools.toUrlParams(sign(map)), + getHeaderMap(), + BiliBiliUtils.RET_MODEL.JSON + ); + System.out.println("任务 " + index + " :" + httpGet); + } + + public AppUserTask startAppTask() { + AppUserTask task = getTaskProgress(); + if (task.getDayTask().getStatus() == 2) { + setUserTaskProgress(0); + } + List taskList = task.getWeekTask(); + taskList.forEach(weekTask -> { + if (weekTask.getStatus() == 2) { + setUserTaskProgress(weekTask.getId()); + } + }); + return task; + } + + public static void main(String[] args) throws Exception { + System.out.println(new BiliBiliAppUtils(QQBotManager.defQQ).startAppTask().toMessageFormat()); + } +} diff --git a/src/main/java/com/yutou/qqbot/bilibili/BiliBiliManga.java b/src/main/java/com/yutou/qqbot/bilibili/BiliBiliManga.java index 9bcd1f7..95f191c 100644 --- a/src/main/java/com/yutou/qqbot/bilibili/BiliBiliManga.java +++ b/src/main/java/com/yutou/qqbot/bilibili/BiliBiliManga.java @@ -2,6 +2,7 @@ package com.yutou.qqbot.bilibili; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; +import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.utlis.HttpTools; import lombok.Data; @@ -12,23 +13,28 @@ import java.util.Timer; import java.util.TimerTask; public class BiliBiliManga { + public BiliBiliManga() { + biliUtils = BiliBiliUtils.getInstance(QQBotManager.defQQ); + } + public static JSONObject sign() { JSONObject body = new JSONObject(); body.put("platform", "android"); - return BiliBiliUtils.http_post("https://manga.bilibili.com/twirp/activity.v1.Activity/ClockIn", HttpTools.toUrlParams(body)); + return BiliBiliUtils.getInstance(QQBotManager.defQQ).http_post("https://manga.bilibili.com/twirp/activity.v1.Activity/ClockIn", HttpTools.toUrlParams(body)); } private static JSONObject getListProductDate() { - return BiliBiliUtils.http_post("https://manga.bilibili.com/twirp/pointshop.v1.Pointshop/ListProduct", ""); + return BiliBiliUtils.getInstance(QQBotManager.defQQ).http_post("https://manga.bilibili.com/twirp/pointshop.v1.Pointshop/ListProduct", ""); } private static boolean isPayMission = false; private static Product missionProduct = new Product(); private static Timer mission = null; - private final List anInterface = new ArrayList<>(); + private static BiliBiliUtils biliUtils = null; + private ObjectInterface anInterface = null; public void addInterface(ObjectInterface objectInterface) { - anInterface.add(objectInterface); + anInterface = objectInterface; } public static boolean isPayMission() { @@ -36,7 +42,7 @@ public class BiliBiliManga { } public static String getMission() { - return missionProduct+" 兑换数量:"+missionProduct.getPayAmount(); + return missionProduct + " 兑换数量:" + missionProduct.getPayAmount(); } public static List getListProduct() { @@ -59,7 +65,7 @@ public class BiliBiliManga { } public static int getMyPoint() { - JSONObject user = BiliBiliUtils.http_post("https://manga.bilibili.com/twirp/pointshop.v1.Pointshop/GetUserPoint", ""); + JSONObject user = biliUtils.http_post("https://manga.bilibili.com/twirp/pointshop.v1.Pointshop/GetUserPoint", ""); if (user != null && user.getInteger("code") == 0) { return user.getJSONObject("data").getInteger("point"); } @@ -70,7 +76,12 @@ public class BiliBiliManga { JSONObject json = new JSONObject(); if (isPayMission) { json.put("code", 2); - json.put("msg", "任务正在进行:" +getMission()); + json.put("msg", "任务正在进行:" + getMission()); + return json; + } + if (biliUtils == null) { + json.put("code", -1); + json.put("msg", "B站未登录"); return json; } int userPoint = getMyPoint(); @@ -107,9 +118,9 @@ public class BiliBiliManga { if (num == 0) { json.put("code", 3); json.put("msg", "商品无货,正在抢购"); - }else { + } else { json.put("code", 0); - json.put("msg", "任务创建成功:"+missionProduct+" 兑换数量:"+num); + json.put("msg", "任务创建成功:" + missionProduct + " 兑换数量:" + num); } return json; } @@ -122,24 +133,18 @@ public class BiliBiliManga { mission.schedule(new TimerTask() { @Override public void run() { - JSONObject post = BiliBiliUtils.http_post("https://manga.bilibili.com/twirp/pointshop.v1.Pointshop/Exchange", HttpTools.toUrlParams(data)); + JSONObject post = biliUtils.http_post("https://manga.bilibili.com/twirp/pointshop.v1.Pointshop/Exchange", HttpTools.toUrlParams(data)); if (post == null) { - for (ObjectInterface objectInterface : anInterface) { - objectInterface.out("网络请求失败,请查看日志"); - } + anInterface.out("网络请求失败,请查看日志"); cancel(); return; } if (post.getInteger("code") == 0) { - for (ObjectInterface mInt : anInterface) { - mInt.out("兑换成功,任务已取消"); - } + anInterface.out("兑换成功,任务已取消"); isPayMission = false; cancel(); } else { - for (ObjectInterface objectInterface : anInterface) { - objectInterface.out("[" + post.getInteger("code") + "]" + post.getString("msg")); - } + anInterface.out("[" + post.getInteger("code") + "]" + post.getString("msg")); } } }, 0, 1000); diff --git a/src/main/java/com/yutou/qqbot/bilibili/BiliBiliUtils.java b/src/main/java/com/yutou/qqbot/bilibili/BiliBiliUtils.java index 3a7ce38..6b4b23a 100644 --- a/src/main/java/com/yutou/qqbot/bilibili/BiliBiliUtils.java +++ b/src/main/java/com/yutou/qqbot/bilibili/BiliBiliUtils.java @@ -2,8 +2,10 @@ package com.yutou.qqbot.bilibili; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; +import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.utlis.*; +import org.brotli.dec.BrotliInputStream; import javax.net.ssl.HttpsURLConnection; import java.io.*; @@ -12,12 +14,13 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.zip.GZIPInputStream; public class BiliBiliUtils { - private static long oldBiliBiliHttpTime = 0; + private long qq; + private long oldBiliBiliHttpTime = 0; public enum HTTP { POST, GET @@ -27,14 +30,22 @@ public class BiliBiliUtils { BYTE, JSON } - public synchronized static JSONObject http_get(String url) { + public BiliBiliUtils(long qq) { + this.qq = qq; + } + + public static BiliBiliUtils getInstance(long qq) { + return new BiliBiliUtils(qq); + } + + public synchronized JSONObject http_get(String url) { try { // Log.i("调用url = "+url); HttpsURLConnection connection = getBiliHttpGet(url, getCookie()); BufferedInputStream stream = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; - int len = 0, size; + int len; while ((len = stream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); outputStream.flush(); @@ -42,8 +53,7 @@ public class BiliBiliUtils { String str = outputStream.toString(StandardCharsets.UTF_8); outputStream.close(); try { - JSONObject json = JSON.parseObject(str); - return json; + return JSON.parseObject(str); } catch (Exception e) { JSONObject json = new JSONObject(); json.put("html", str); @@ -61,15 +71,15 @@ public class BiliBiliUtils { return null; } - public static JSONObject http_post(String url, String body) { + public JSONObject http_post(String url, String body) { return http(url, HTTP.POST, body, RET_MODEL.JSON); } - public static T http(String url, HTTP model, String body, RET_MODEL ret_model) { + public T http(String url, HTTP model, String body, RET_MODEL ret_model) { return http(url, model, body, null, ret_model); } - public static T http(String url, HTTP model, String body, Map headers, RET_MODEL ret_model) { + public T http(String url, HTTP model, String body, Map headers, RET_MODEL ret_model) { JSONObject json = null; BufferedInputStream stream = null; ByteArrayOutputStream outputStream = null; @@ -101,9 +111,9 @@ public class BiliBiliUtils { for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } + } else { + connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } - System.out.println("url = " + url); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); if (!StringUtils.isEmpty(body)) { connectionOutputStream = connection.getOutputStream(); @@ -114,7 +124,13 @@ public class BiliBiliUtils { if (connection.getResponseCode() == 400) { return null; } - stream = new BufferedInputStream(connection.getInputStream()); + if (connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip")) { + stream = new BufferedInputStream(new GZIPInputStream(connection.getInputStream())); + } else if (connection.getContentEncoding() != null && connection.getContentEncoding().contains("br")) { + stream = new BufferedInputStream(new BrotliInputStream(connection.getInputStream())); + } else { + stream = new BufferedInputStream(connection.getInputStream()); + } outputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len = 0, size; @@ -162,12 +178,11 @@ public class BiliBiliUtils { return null; } - public static String getCookie() { - if (StringUtils.isEmpty(ConfigTools.readFile(new File("bilibili.cookie")))) { - + public String getCookie() { + if (StringUtils.isEmpty(ConfigTools.readFile(new File(qq + "_bilibili.cookie")))) { return ""; } - JSONObject json = JSON.parseObject(ConfigTools.readFile(new File("bilibili.cookie"))); + JSONObject json = JSON.parseObject(ConfigTools.readFile(new File(qq + "_bilibili.cookie"))); StringBuilder builder = new StringBuilder(); for (String s : json.keySet()) { builder.append(s).append("=").append(json.getString(s)).append(";"); @@ -176,7 +191,7 @@ public class BiliBiliUtils { return builder.toString(); } - public static HttpURLConnection getBiliHttpPost(String url, String cookie) throws Exception { + public HttpURLConnection getBiliHttpPost(String url, String cookie) throws Exception { if (System.currentTimeMillis() - oldBiliBiliHttpTime < 1000) { try { Thread.sleep(500); @@ -193,7 +208,7 @@ public class BiliBiliUtils { return connection; } - public static HttpsURLConnection getBiliHttpGet(String url, String cookie) throws IOException { + public HttpsURLConnection getBiliHttpGet(String url, String cookie) throws IOException { if (System.currentTimeMillis() - oldBiliBiliHttpTime < 1000) { try { Thread.sleep(500); @@ -210,7 +225,7 @@ public class BiliBiliUtils { return connection; } - public static File download(final String url, final String saveName, boolean isProxy) { + public File download(final String url, final String saveName, boolean isProxy) { File jar = null; try { File savePath = new File(HttpTools.downloadPath + saveName); @@ -262,7 +277,7 @@ public class BiliBiliUtils { return null; } - public static void download_ffmpeg(final List url, final String saveName) { + public void download_ffmpeg(final List url, final String saveName) { new Thread(() -> { StringBuilder builder = new StringBuilder(); builder.append(ConfigTools.load(ConfigTools.CONFIG, "ffmpeg", String.class)).append(" "); @@ -296,7 +311,7 @@ public class BiliBiliUtils { } - private static void setConnection(String cookie, HttpURLConnection connection) { + private void setConnection(String cookie, HttpURLConnection connection) { connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); connection.addRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); connection.addRequestProperty("Cache-Control", "max-age=0"); @@ -307,8 +322,8 @@ public class BiliBiliUtils { connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"); } - public static JSONObject getLoginInfo() { - JSONObject jsonObject = BiliBiliUtils.http_get("https://api.bilibili.com/x/web-interface/nav"); + public JSONObject getLoginInfo() { + JSONObject jsonObject = http_get("https://api.bilibili.com/x/web-interface/nav"); if (jsonObject == null) { jsonObject = new JSONObject(); jsonObject.put("code", "-1"); @@ -317,9 +332,9 @@ public class BiliBiliUtils { return jsonObject; } - public static void main(String[] args) { + public void main(String[] args) { /* String url="https://xy218x85x123x8xy.mcdn.bilivideo.cn:4483/upgcxcode/12/12/17281212/17281212-16-80.flv?e=ig8euxZM2rNcNbNBhbdVhwdlhbUghwdVhoNvNC8BqJIzNbfqXBvEqxTEto8BTrNvN0GvT90W5JZMkX_YN0MvXg8gNEV4NC8xNEV4N03eN0B5tZlqNxTEto8BTrNvNeZVuJ10Kj_g2UB02J0mN0B5tZlqNCNEto8BTrNvNC7MTX502C8f2jmMQJ6mqF2fka1mqx6gqj0eN0B599M=&uipk=5&nbs=1&deadline=1660538573&gen=playurlv2&os=mcdn&oi=2936701972&trid=00006f9623cac1514d8ea18fba3a15a756cau&mid=96300&platform=pc&upsig=25ddd1da610960e8e1d2e80dc97c2361&uparams=e,uipk,nbs,deadline,gen,os,oi,trid,mid,platform&mcdnid=11000101&bvc=vod&nettype=0&orderid=0,2&agrr=1&bw=253116&logo=A0000400&requestFrom=BILIBILI_HELPER_2.5.8"; - File file=BiliBiliUtils.download(url,"16.mp4",false); + File file=download(url,"16.mp4",false); System.out.println("file.getAbsolutePath() = " + file.getAbsolutePath());*/ /* System.out.println(getLiveRoom(42062)); System.out.println("--------------------------------------------"); @@ -328,44 +343,44 @@ public class BiliBiliUtils { System.out.println("sign = " + sign); } - public static boolean sendLiveDanmu(long roomId, String msg) { + public boolean sendLiveDanmu(long roomId, String msg) { JSONObject body = new JSONObject(); body.put("msg", msg); body.put("roomid", roomId); body.put("color", 16777215); body.put("fontsize", 25); body.put("rnd", System.currentTimeMillis() / 1000); - body.put("csrf", BiliLogin.getCookieToken()); - body.put("csrf_token", BiliLogin.getCookieToken()); - JSONObject post = BiliBiliUtils.http_post("https://api.live.bilibili.com/msg/send", HttpTools.toUrlParams(body)); + body.put("csrf", BiliLogin.getCookieToken(qq)); + body.put("csrf_token", BiliLogin.getCookieToken(qq)); + JSONObject post = http_post("https://api.live.bilibili.com/msg/send", HttpTools.toUrlParams(body)); return post.getInteger("code") == 0; } - public static String liveSignIn() { + public String liveSignIn() { //{"code":0,"data":{"coin":1,"gold":19500,"silver":106394,"tid":"Silver2Coin22101413201169763005873"},"message":"兑换成功"} JSONObject body = new JSONObject(); - body.put("csrf", BiliLogin.getCookieToken()); - body.put("csrf_token", BiliLogin.getCookieToken()); - JSONObject post = BiliBiliUtils.http_post("https://api.live.bilibili.com/xlive/revenue/v1/wallet/silver2coin", HttpTools.toUrlParams(body)); - JSONObject post_ = BiliBiliUtils.http_get("https://api.live.bilibili.com/xlive/web-ucenter/v1/sign/DoSign"); + body.put("csrf", BiliLogin.getCookieToken(qq)); + body.put("csrf_token", BiliLogin.getCookieToken(qq)); + JSONObject post = http_post("https://api.live.bilibili.com/xlive/revenue/v1/wallet/silver2coin", HttpTools.toUrlParams(body)); + JSONObject post_ = http_get("https://api.live.bilibili.com/xlive/web-ucenter/v1/sign/DoSign"); return post.getString("message") + "|" + post_.getString("message"); } - public static JSONObject getLiveRoom(int roomId) { + public JSONObject getLiveRoom(int roomId) { JSONObject body = new JSONObject(); body.put("room_id", roomId); - body.put("csrf", BiliLogin.getCookieToken()); - body.put("csrf_token", BiliLogin.getCookieToken()); - return BiliBiliUtils.http_post("https://api.live.bilibili.com/room/v1/Room/get_info", HttpTools.toUrlParams(body)); + body.put("csrf", BiliLogin.getCookieToken(qq)); + body.put("csrf_token", BiliLogin.getCookieToken(qq)); + return http_post("https://api.live.bilibili.com/room/v1/Room/get_info", HttpTools.toUrlParams(body)); } - public static JSONObject getUserInfo(int mid) { + public JSONObject getUserInfo(int mid) { JSONObject body = new JSONObject(); body.put("mid", mid); - return BiliBiliUtils.http_get("https://api.bilibili.com/x/space/acc/info?" + HttpTools.toUrlParams(body)); + return http_get("https://api.bilibili.com/x/space/acc/info?" + HttpTools.toUrlParams(body)); } - public static boolean checkLiveRoom(int roomId) { + public boolean checkLiveRoom(int roomId) { JSONObject post = getLiveRoom(roomId); return post.getInteger("code") == 0; } diff --git a/src/main/java/com/yutou/qqbot/bilibili/BiliLogin.java b/src/main/java/com/yutou/qqbot/bilibili/BiliLogin.java index 153b2f4..6005db6 100644 --- a/src/main/java/com/yutou/qqbot/bilibili/BiliLogin.java +++ b/src/main/java/com/yutou/qqbot/bilibili/BiliLogin.java @@ -15,73 +15,92 @@ import java.util.TimerTask; public class BiliLogin { + BiliBiliUtils biliUtils; + private long qq; - public JSONObject login(){ - JSONObject login= JSON.parseObject(HttpTools.get("https://passport.bilibili.com/qrcode/getLoginUrl")); - JSONObject json=new JSONObject(); - json.put("code",login.getInteger("code")); - json.put("url",login.getJSONObject("data").getString("url")); + + public BiliLogin(Long qq) { + biliUtils = BiliBiliUtils.getInstance(qq); + this.qq=qq; + } + + public JSONObject login() { + JSONObject login = JSON.parseObject(HttpTools.get("https://passport.bilibili.com/qrcode/getLoginUrl")); + JSONObject json = new JSONObject(); + json.put("code", login.getInteger("code")); + json.put("url", login.getJSONObject("data").getString("url")); new Thread(() -> waitLogin(login.getJSONObject("data").getString("oauthKey"))).start(); return json; } - public void waitLogin(String oauthKey){ - long time=System.currentTimeMillis(); - String bd="gourl=https%3A%2F%2Fpassport.bilibili.com%2Fajax%2FminiLogin%2Fredirect&oauthKey="+oauthKey; + public void waitLogin(String oauthKey) { + long time = System.currentTimeMillis(); + String bd = "gourl=https%3A%2F%2Fpassport.bilibili.com%2Fajax%2FminiLogin%2Fredirect&oauthKey=" + oauthKey; new Timer().schedule(new TimerTask() { @Override public void run() { - if((System.currentTimeMillis()-time)>5*60*1000){ + if ((System.currentTimeMillis() - time) > 5 * 60 * 1000) { cancel(); return; } - JSONObject json=JSON.parseObject(HttpTools.post("https://passport.bilibili.com/qrcode/getLoginInfo",bd.getBytes(StandardCharsets.UTF_8))); - if(json.containsKey("code")&&json.getInteger("code")==0){ + JSONObject json = JSON.parseObject(HttpTools.post("https://passport.bilibili.com/qrcode/getLoginInfo", bd.getBytes(StandardCharsets.UTF_8))); + if (json.containsKey("code") && json.getInteger("code") == 0) { System.out.println("json = " + json); - String _url=json.getJSONObject("data").getString("url"); - Map map=HttpTools.getUrlParams(_url); + String _url = json.getJSONObject("data").getString("url"); + Map map = HttpTools.getUrlParams(_url); - JSONObject cookie=new JSONObject(); - JSONArray array=new JSONArray(); + JSONObject cookie = new JSONObject(); + JSONArray array = new JSONArray(); for (String key : map.keySet()) { - cookie.put(key,map.get(key)); + cookie.put(key, map.get(key)); } System.out.println(array); + if (biliUtils == null) { + biliUtils = BiliBiliUtils.getInstance(qq); + } + assert biliUtils != null; - JSONObject tmp=BiliBiliUtils.http_post(_url,""); + JSONObject tmp = biliUtils.http_post(_url, ""); System.out.println("tmp = " + tmp); - if(tmp==null){ + if (tmp == null) { cancel(); return; } - String sid=tmp.getString("cookie"); - sid=sid.split("sid=")[1]; - sid=sid.split(";")[0]; - cookie.put("sid",sid); - cookie.put("Domain",".bilibili.com"); - ConfigTools.saveFile(new File("bilibili.cookie"),cookie.toJSONString()); + String sid = tmp.getString("cookie"); + sid = sid.split("sid=")[1]; + sid = sid.split(";")[0]; + cookie.put("sid", sid); + cookie.put("Domain", ".bilibili.com"); + ConfigTools.saveFile(new File(qq + "_bilibili.cookie"), cookie.toJSONString()); cancel(); } } - },0,3000); + }, 0, 3000); } - public boolean testLogin(){ - JSONObject jsonObject = BiliBiliUtils.getLoginInfo(); - return jsonObject.getInteger("code")==0; + + public boolean testLogin() { + if (biliUtils == null) { + return false; + } + JSONObject jsonObject = biliUtils.getLoginInfo(); + return jsonObject.getInteger("code") == 0; } - public static String getCookieToken(){ - if (StringUtils.isEmpty(ConfigTools.readFile(new File("bilibili.cookie")))) { + + public static String getCookieToken(Long qq) { + if (StringUtils.isEmpty(ConfigTools.readFile(new File(qq+"_bilibili.cookie")))) { return null; } - JSONObject json = JSON.parseObject(ConfigTools.readFile(new File("bilibili.cookie"))); + JSONObject json = JSON.parseObject(ConfigTools.readFile(new File(qq+"_bilibili.cookie"))); return json.getString("bili_jct"); } public static void main(String[] args) { - BiliLogin login = new BiliLogin(); + BiliLogin login = new BiliLogin(583819556L); boolean testLogin = login.testLogin(); System.out.println("testLogin = " + testLogin); + // JSONObject json = login.login(); + // QRCodeUtils.createQRCode("bili_login", json.getString("url")); } } diff --git a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java index b60f98e..5bf875d 100644 --- a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java +++ b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java @@ -2,7 +2,8 @@ package com.yutou.qqbot.models.BiliBili; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; -import com.yutou.qqbot.bilibili.BiliBiliManga; +import com.yutou.qqbot.bilibili.AppUserTask; +import com.yutou.qqbot.bilibili.BiliBiliAppUtils; import com.yutou.qqbot.bilibili.BiliBiliUtils; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.RedisTools; @@ -20,6 +21,7 @@ public class BiliBiliLive extends Model { @Override public String[] getUsePowers() { return new String[]{ + Model.QQGroupCommands.BILI_LIVE_DANMU_LIST, Model.QQGroupCommands.BILI_LIVE_DANMU_SEND, QQGroupCommands.BILI_LIVE_DANMU_DEL }; @@ -34,32 +36,45 @@ public class BiliBiliLive extends Model { public synchronized void onTime(Long qq, String time) { super.onTime(qq, time); if ("00:01:00".equals(time)) { - QQBotManager.getInstance().sendMessage(qq, BiliBiliUtils.liveSignIn()); - Set biliLive = RedisTools.list_get("bili_live"); - StringBuilder builder = new StringBuilder(); - for (String id : biliLive) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - boolean sign = BiliBiliUtils.sendLiveDanmu(Integer.parseInt(id), "打卡"); - builder.append("BiliLiveSign ").append(id).append(":").append(sign).append("\n"); - } - QQBotManager.getInstance().sendMessage(qq, builder.toString()); + signLive(QQBotManager.defQQ, qq); } } + private void signLive(long qq, long sendQQ) { + BiliBiliUtils biliUtils = BiliBiliUtils.getInstance(qq); + QQBotManager.getInstance().sendMessage(sendQQ, biliUtils.liveSignIn()); + Set biliLive = RedisTools.list_get("bili_live"); + StringBuilder builder = new StringBuilder(); + for (String id : biliLive) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + boolean sign = biliUtils.sendLiveDanmu(Integer.parseInt(id), "打卡"); + builder.append("BiliLiveSign").append(id).append(":").append(sign).append("\n"); + } + QQBotManager.getInstance().sendMessage(sendQQ, builder.toString()); + AppUserTask task = new BiliBiliAppUtils(QQBotManager.defQQ).startAppTask(); + builder = new StringBuilder(); + builder.append("执行APP任务").append("\n").append(task.toMessageFormat()); + QQBotManager.getInstance().sendMessage(sendQQ, builder.toString()); + } + @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - if (!msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_SEND) && !msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_DEL)) { + if (!msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_SEND) && + !msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_DEL) && + !msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_LIST)) { return; } - if(msg.equals(QQGroupCommands.BILI_LIVE_DANMU_SEND+"debug")){ - onTime(qq,"00:01:00"); + if (msg.equals(QQGroupCommands.BILI_LIVE_DANMU_SEND)) { + signLive(user, qq); return; } + + BiliBiliUtils biliUtils = BiliBiliUtils.getInstance(isGroup ? event.getSource().getFromId() : qq); StringBuilder message; message = new StringBuilder(); try { @@ -67,11 +82,13 @@ public class BiliBiliLive extends Model { if (msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_DEL)) { isDel = true; msg = msg.replace(QQGroupCommands.BILI_LIVE_DANMU_DEL, "").trim(); - } else { + } else if (msg.startsWith(QQGroupCommands.BILI_LIVE_DANMU_SEND)) { msg = msg.replace(QQGroupCommands.BILI_LIVE_DANMU_SEND, "").trim(); + } else { + msg = "0"; } Integer roomId = Integer.parseInt(msg); - if (BiliBiliUtils.checkLiveRoom(roomId)) { + if (biliUtils.checkLiveRoom(roomId) && roomId != 0) { if (isDel && RedisTools.list_isExist("bili_live", roomId + "")) { RedisTools.list_remove("bili_live", roomId + ""); message.append("直播签到删除成功").append("\n"); @@ -79,7 +96,7 @@ public class BiliBiliLive extends Model { RedisTools.list_add("bili_live", roomId + ""); message.append("直播签到添加成功").append("\n"); } - } else { + } else if (roomId != 0) { message.append("直播签到操作失败\n"); } } catch (Exception e) { @@ -90,8 +107,8 @@ public class BiliBiliLive extends Model { for (String id : biliLive) { message.append(id) .append(":") - .append(BiliBiliUtils.getUserInfo( - BiliBiliUtils.getLiveRoom(Integer.parseInt(id)) + .append(biliUtils.getUserInfo( + biliUtils.getLiveRoom(Integer.parseInt(id)) .getJSONObject("data") .getInteger("uid")) .getJSONObject("data") diff --git a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java index e23313b..2dd41ff 100644 --- a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java +++ b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java @@ -3,6 +3,7 @@ package com.yutou.qqbot.models.BiliBili; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import com.yutou.qqbot.Annotations.UseModel; +import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.bilibili.*; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.models.Model; @@ -23,6 +24,18 @@ public class BiliVideo extends Model { public String downloadPath = "tmp"; List danmuDatas = new ArrayList<>(); long danmuNextTime = 0; + private BiliBiliUtils biliUtils; + private long qq; + + public BiliVideo(long qq) { + this.qq = qq; + biliUtils = BiliBiliUtils.getInstance(qq); + } + + public BiliVideo() { + this.qq = QQBotManager.defQQ; + biliUtils = BiliBiliUtils.getInstance(qq); + } @Override public boolean isUserPublic() { @@ -44,7 +57,7 @@ public class BiliVideo extends Model { } public void downVideo(String url, boolean downDanmu, boolean merge) { - if (!new BiliLogin().testLogin()) { + if (biliUtils == null || !new BiliLogin(qq).testLogin()) { System.err.println("未登录"); return; } @@ -196,19 +209,19 @@ public class BiliVideo extends Model { if (tmp.exists()) { return; } - JSONObject http = BiliBiliUtils.http("https://api.bilibili.com/x/player/playurl?" + HttpTools.toUrlParams(json), BiliBiliUtils.HTTP.GET, null, BiliBiliUtils.RET_MODEL.JSON); + JSONObject http = biliUtils.http("https://api.bilibili.com/x/player/playurl?" + HttpTools.toUrlParams(json), BiliBiliUtils.HTTP.GET, null, BiliBiliUtils.RET_MODEL.JSON); if (http.getInteger("code") == 0) { JSONObject data = http.getJSONObject("data"); JSONObject dash = data.getJSONObject("dash"); JSONObject video = dash.getJSONArray("video").getJSONObject(0); JSONObject audio = dash.getJSONArray("audio").getJSONObject(0); - File videoFile = BiliBiliUtils.download(video.getString("baseUrl"), eps.getString("title") + "_video.mp4", false); + File videoFile = biliUtils.download(video.getString("baseUrl"), eps.getString("title") + "_video.mp4", false); if (videoFile == null) { downVideo(json, eps); return; } - File audioFile = BiliBiliUtils.download(audio.getString("baseUrl"), eps.getString("title") + "_audio.mp3", false); + File audioFile = biliUtils.download(audio.getString("baseUrl"), eps.getString("title") + "_audio.mp3", false); if (audioFile == null) { videoFile.delete(); downVideo(json, eps); @@ -255,7 +268,7 @@ public class BiliVideo extends Model { private List getDanmu(JSONObject json) { try { - byte[] http = BiliBiliUtils.http("https://api.bilibili.com/x/v2/dm/web/seg.so?" + HttpTools.toUrlParams(json), BiliBiliUtils.HTTP.GET, null, BiliBiliUtils.RET_MODEL.BYTE); + byte[] http = biliUtils.http("https://api.bilibili.com/x/v2/dm/web/seg.so?" + HttpTools.toUrlParams(json), BiliBiliUtils.HTTP.GET, null, BiliBiliUtils.RET_MODEL.BYTE); VideoDanMu.DmSegMobileReply parse = VideoDanMu.DmSegMobileReply.parseFrom(http); return parse.getElemsList(); } catch (Exception e) { @@ -298,13 +311,13 @@ public class BiliVideo extends Model { } public JSONObject getVideoInfo(String url) { - if (!new BiliLogin().testLogin()) { + if (!new BiliLogin(qq).testLogin()) { System.err.println("未登录"); return null; } JSONObject json = buildJSON(url); if (json != null) { - return BiliBiliUtils.http("https://api.bilibili.com/x/web-interface/view?" + HttpTools.toUrlParams(json), BiliBiliUtils.HTTP.GET, null, BiliBiliUtils.RET_MODEL.JSON); + return biliUtils.http("https://api.bilibili.com/x/web-interface/view?" + HttpTools.toUrlParams(json), BiliBiliUtils.HTTP.GET, null, BiliBiliUtils.RET_MODEL.JSON); } return null; } @@ -336,8 +349,8 @@ public class BiliVideo extends Model { public static void main(String[] args) { - BiliVideo video = new BiliVideo(); - JSONObject login = new BiliLogin().login(); + BiliVideo video = new BiliVideo(QQBotManager.defQQ); + JSONObject login = new BiliLogin(QQBotManager.defQQ).login(); System.out.println(login); //岚少 480 //video.downVideo("https://www.bilibili.com/video/BV1Ps411m7pt?spm_id_from=333.999.0.0"); diff --git a/src/main/java/com/yutou/qqbot/models/Model.java b/src/main/java/com/yutou/qqbot/models/Model.java index c7023ad..e0ef13f 100644 --- a/src/main/java/com/yutou/qqbot/models/Model.java +++ b/src/main/java/com/yutou/qqbot/models/Model.java @@ -1,7 +1,9 @@ package com.yutou.qqbot.models; +import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.QQNumberManager; import com.yutou.qqbot.interfaces.ModelInterface; +import net.mamoe.mirai.Bot; import net.mamoe.mirai.event.events.GroupMessageEvent; import net.mamoe.mirai.event.events.MessageEvent; import net.mamoe.mirai.message.data.At; @@ -35,15 +37,16 @@ public abstract class Model implements ModelInterface { public final static String QQ_BANGUMI_INFO = "!保存动画信息>"; public final static String QQ_MOYU = "!摸鱼"; - public final static String BILI_LIVE_DANMU_SEND="!b站签到"; - public final static String BILI_LIVE_DANMU_DEL="!b站签到删除"; + public final static String BILI_LIVE_DANMU_SEND = "!b站签到"; + public final static String BILI_LIVE_DANMU_LIST = "!b站列表"; + public final static String BILI_LIVE_DANMU_DEL = "!b站签到删除"; - public final static String QQ_WOODEN="!电子木鱼"; - public final static String QQ_TIMEOUT="!timer"; + public final static String QQ_WOODEN = "!电子木鱼"; + public final static String QQ_TIMEOUT = "!timer"; } - public static class QQFromCommands { + public static class QQFromCommands { public static final String TURNIP_PROPHET = "大头菜"; public static final String TSDM_PAY = "!tsdm"; public static final String BAIDU_DOWN = "!bd"; @@ -58,9 +61,11 @@ public abstract class Model implements ModelInterface { public static List> classList; long group; + static { - classList=new ArrayList<>(); + classList = new ArrayList<>(); } + public Model() { if (!classList.contains(getClass())) { classList.add(getClass()); @@ -71,14 +76,14 @@ public abstract class Model implements ModelInterface { public String msg; protected boolean isGroupPower = false; private boolean isGroup; - private Long user; + public Long user; public void onMessage(Long qq, MessageEvent event, boolean isGroup) { msg = event.getMessage().contentToString(); msg = msg.replace("!", "!").trim(); this.isGroup = isGroup; if (isGroup) { - user=event.getSource().getFromId(); + user = event.getSource().getFromId(); GroupMessageEvent groupEvent = (GroupMessageEvent) event; group = groupEvent.getGroup().getId(); if (QQNumberManager.getManager().isExistsPower(group, msg.split(" ")[0])) { @@ -87,7 +92,7 @@ public abstract class Model implements ModelInterface { } } - public synchronized void onTime(Long qq,String time) { + public synchronized void onTime(Long qq, String time) { } public static StringBuilder getCommands(Class commands) { diff --git a/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java b/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java index 110872a..fb431c8 100644 --- a/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java +++ b/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java @@ -36,7 +36,7 @@ public class BiliBiliMangeSign extends Model { super.onMessage(qq, event, isGroup); if (msg.equals(QQFromCommands.BILI_MANGA_SIGN)) { String msg; - if (new BiliLogin().testLogin()) { + if (new BiliLogin(user).testLogin()) { if (BiliBiliManga.sign() == null) { msg = "B站漫画已经签到过了"; } else { @@ -44,7 +44,7 @@ public class BiliBiliMangeSign extends Model { } QQBotManager.getInstance().sendMessage(qq, msg); } else { - String url = new BiliLogin().login().getString("url"); + String url = new BiliLogin(user).login().getString("url"); File code = QRCodeUtils.createQRCode("bili_login", url); QQBotManager.getInstance().sendMessage(code, qq, "B站未登录,请扫码登陆后再试"); } @@ -118,7 +118,7 @@ public class BiliBiliMangeSign extends Model { public void onTime(Long qq,String time) { super.onTime(qq,time); if ("00:01:00".equals(time)) { - if (new BiliLogin().testLogin()) { + if (new BiliLogin(QQBotManager.defQQ).testLogin()) { String msg; if (BiliBiliManga.sign() == null) { msg = "B站漫画已经签到过了"; diff --git a/src/main/java/com/yutou/qqbot/utlis/RSAUtils.java b/src/main/java/com/yutou/qqbot/utlis/RSAUtils.java new file mode 100644 index 0000000..64d8adb --- /dev/null +++ b/src/main/java/com/yutou/qqbot/utlis/RSAUtils.java @@ -0,0 +1,136 @@ +package com.yutou.qqbot.utlis; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import java.io.ByteArrayOutputStream; +import java.security.*; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashMap; +import java.util.Map; + +public class RSAUtils { + /** + * 加密算法RSA + */ + public static final String KEY_ALGORITHM = "RSA"; + + /** + * 签名算法 + */ + public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; + + /** + * 获取公钥的key + */ + private static final String PUBLIC_KEY = "RSAPublicKey"; + + /** + * 获取私钥的key + */ + private static final String PRIVATE_KEY = "RSAPrivateKey"; + + /** + * RSA 密钥位数 + */ + private static final int KEY_SIZE = 1024; + + /** + * RSA最大解密密文大小 + */ + private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8; + + /** + * RSA最大加密明文大小 + */ + private static final int MAX_ENCRYPT_BLOCK = MAX_DECRYPT_BLOCK - 11; + private static Map keyMap=new HashMap<>(); + + /** + * 随机生成密钥对 + * @throws NoSuchAlgorithmException + */ + public static void getKeyPair() throws Exception { + //KeyPairGenerator类用于生成公钥和密钥对,基于RSA算法生成对象 + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); + //初始化密钥对生成器,密钥大小为96-1024位 + keyPairGen.initialize(1024,new SecureRandom()); + //生成一个密钥对,保存在keyPair中 + KeyPair keyPair = keyPairGen.generateKeyPair(); + PrivateKey privateKey = keyPair.getPrivate();//得到私钥 + PublicKey publicKey = keyPair.getPublic();//得到公钥 + //得到公钥字符串 + String publicKeyString=new String(Base64.encodeBase64(publicKey.getEncoded())); + //得到私钥字符串 + String privateKeyString=new String(Base64.encodeBase64(privateKey.getEncoded())); + //将公钥和私钥保存到Map + keyMap.put(0,publicKeyString);//0表示公钥 + keyMap.put(1,privateKeyString);//1表示私钥 + } + /** + *

+ * 公钥加密 + *

+ * + * @param str 源数据 + * @param publicKey 公钥(BASE64编码) + * @return + * @throws Exception + */ + public static String encryptByPublicKey(String str, String publicKey) throws Exception { + publicKey=publicKey.replace("-----BEGIN PUBLIC KEY-----","").replace("-----END PUBLIC KEY-----",""); + byte[] data=Base64.decodeBase64(str); + byte[] keyBytes = Base64.decodeBase64(publicKey); + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); + Key publicK = keyFactory.generatePublic(x509KeySpec); + // 对数据加密 + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(Cipher.ENCRYPT_MODE, publicK); + int inputLen = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段加密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + byte[] encryptedData = out.toByteArray(); + out.close(); + return new String(Base64.encodeBase64(encryptedData)); + } + + /** + * RSA私钥解密 + * + * @param str + * 加密字符串 + * @param privateKey + * 私钥 + * @return 铭文 + * @throws Exception + * 解密过程中的异常信息 + */ + public static String decrypt(String str,String privateKey) throws Exception { + //Base64解码加密后的字符串 + byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); + //Base64编码的私钥 + byte[] decoded = Base64.decodeBase64(privateKey); + PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); + //RSA解密 + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE,priKey); + String outStr=new String(cipher.doFinal(inputByte)); + return outStr; + + } +} diff --git a/src/main/java/com/yutou/qqbot/utlis/RedisTools.java b/src/main/java/com/yutou/qqbot/utlis/RedisTools.java index 0cc9ea8..924a58a 100644 --- a/src/main/java/com/yutou/qqbot/utlis/RedisTools.java +++ b/src/main/java/com/yutou/qqbot/utlis/RedisTools.java @@ -168,28 +168,46 @@ public class RedisTools { } public static Set list_get(String listName) { - Jedis jedis = getRedis(); - jedis.select(QQBOT_USER); - Set set = jedis.smembers(listName); - jedis.close(); - if (set == null) { + Set set; + try { + Jedis jedis = getRedis(); + jedis.select(QQBOT_USER); + set = jedis.smembers(listName); + jedis.close(); + if (set == null) { + set = new HashSet<>(); + } + } catch (Exception e) { + e.printStackTrace(); set = new HashSet<>(); } + return set; } public static boolean list_remove(String listName, String... value) { - Jedis jedis = getRedis(); - jedis.select(QQBOT_USER); - long index = jedis.srem(listName, value); - jedis.close(); + long index = 0; + try { + Jedis jedis = getRedis(); + jedis.select(QQBOT_USER); + index = jedis.srem(listName, value); + jedis.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return index != 0; } public static boolean list_isExist(String listName, String value) { - Jedis jedis = getRedis(); - boolean flag = jedis.sismember(listName, value); - jedis.close(); + boolean flag = false; + try { + Jedis jedis = getRedis(); + flag = jedis.sismember(listName, value); + jedis.close(); + } catch (Exception e) { + e.printStackTrace(); + } return flag; }