新增B站漫画签到

This commit is contained in:
Yutousama 2022-04-08 02:26:29 +08:00
parent d31534311f
commit abfe65a534
12 changed files with 423 additions and 15 deletions

10
pom.xml
View File

@ -56,7 +56,6 @@
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
@ -96,6 +95,11 @@
<version>1.15</version> <version>1.15</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies> </dependencies>
@ -115,7 +119,9 @@
<configuration> <configuration>
<tasks> <tasks>
<echo>复制正式文件</echo> <echo>复制正式文件</echo>
<copy file="src/main/resources/application.properties.release" tofile="${project.build.outputDirectory}/application.properties" overwrite="true"/> <copy file="src/main/resources/application.properties.release"
tofile="${project.build.outputDirectory}/application.properties"
overwrite="true"/>
</tasks> </tasks>
</configuration> </configuration>
</execution> </execution>

View File

@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class QQBotApplication { public class QQBotApplication {
public static final String version="QQBot v.1.2.10.1"; public static final String version="QQBot v.1.2.11";
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("version = " + version); System.out.println("version = " + version);
SpringApplication.run(QQBotApplication.class, args); SpringApplication.run(QQBotApplication.class, args);

View File

@ -7,6 +7,7 @@ import com.yutou.qqbot.models.Commands.Bangumi;
import com.yutou.qqbot.models.Commands.BTDownload; import com.yutou.qqbot.models.Commands.BTDownload;
import com.yutou.qqbot.models.Commands.System.*; import com.yutou.qqbot.models.Commands.System.*;
import com.yutou.qqbot.models.Model; import com.yutou.qqbot.models.Model;
import com.yutou.qqbot.models.WebSign.BiliBiliMangeSign;
import com.yutou.qqbot.models.WebSign.Tsdm; import com.yutou.qqbot.models.WebSign.Tsdm;
import com.yutou.qqbot.models.XiaoMi.MiRouter; import com.yutou.qqbot.models.XiaoMi.MiRouter;
import com.yutou.qqbot.models.setu.GetSeTu; import com.yutou.qqbot.models.setu.GetSeTu;
@ -49,6 +50,7 @@ public class QQBotManager {
Model.classList.add(MiRouter.class); Model.classList.add(MiRouter.class);
Model.classList.add(GetSeTu.class); Model.classList.add(GetSeTu.class);
Model.classList.add(BTDownload.class); Model.classList.add(BTDownload.class);
Model.classList.add(BiliBiliMangeSign.class);
} }
private static QQBotManager botManager = null; private static QQBotManager botManager = null;
private Bot bot; private Bot bot;

View File

@ -0,0 +1,16 @@
package com.yutou.qqbot.bilibili;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.utlis.HttpTools;
public class BiliBiliManga {
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));
}
public static void main(String[] args) {
BiliBiliManga.sign();
}
}

View File

@ -0,0 +1,173 @@
package com.yutou.qqbot.bilibili;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.utlis.ConfigTools;
import org.springframework.util.StringUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class BiliBiliUtils {
private static long oldBiliBiliHttpTime = 0;
public synchronized static JSONObject http_get(String url) {
try {
// Log.i("调用url = "+url);
HttpURLConnection connection = getBiliHttpGet(url, getCookie());
BufferedInputStream stream = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0, size;
while ((len = stream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
String str = outputStream.toString(StandardCharsets.UTF_8);
outputStream.close();
try {
JSONObject json = JSON.parseObject(str);
return json;
} catch (Exception e) {
JSONObject json = new JSONObject();
json.put("html", str);
return json;
} finally {
stream.close();
connection.disconnect();
}
} catch (IOException e) {
//com.yutou.bilibili.Tools.Log.e(e);
e.printStackTrace();
}
return null;
}
public static JSONObject http_post(String url, String body) {
JSONObject json = null;
try {
if (System.currentTimeMillis() - oldBiliBiliHttpTime < 1000) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
oldBiliBiliHttpTime = System.currentTimeMillis();
}
HttpURLConnection connection = getBiliHttpPost(url, getCookie());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
OutputStream connectionOutputStream = null;
if (!StringUtils.isEmpty(body)) {
connectionOutputStream = connection.getOutputStream();
connectionOutputStream.write(body.getBytes(StandardCharsets.UTF_8));
connectionOutputStream.flush();
}
connection.connect();
if(connection.getResponseCode()==400){
return null;
}
BufferedInputStream stream = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0, size;
while ((len = stream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
String str = outputStream.toString(StandardCharsets.UTF_8);
outputStream.close();
try {
json = JSON.parseObject(str);
json.put("cookie", connection.getHeaderField("Set-Cookie"));
return json;
} catch (Exception e) {
json = new JSONObject();
json.put("html", str);
json.put("cookie", connection.getHeaderField("Set-Cookie"));
return json;
} finally {
stream.close();
if (connectionOutputStream != null) {
connectionOutputStream.close();
}
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
public static String getCookie() {
if (StringUtils.isEmpty(ConfigTools.readFile(new File("bilibili.cookie")))) {
return "";
}
JSONObject json = JSONObject.parseObject(ConfigTools.readFile(new File("bilibili.cookie")));
StringBuilder builder = new StringBuilder();
for (String s : json.keySet()) {
builder.append(s).append("=").append(json.getString(s)).append(";");
}
return builder.toString();
}
public static HttpURLConnection getBiliHttpPost(String url, String cookie) throws Exception {
if (System.currentTimeMillis() - oldBiliBiliHttpTime < 1000) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
oldBiliBiliHttpTime = System.currentTimeMillis();
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
setConnection(cookie, connection);
return connection;
}
public static HttpURLConnection getBiliHttpGet(String url, String cookie) throws IOException {
if (System.currentTimeMillis() - oldBiliBiliHttpTime < 1000) {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
oldBiliBiliHttpTime = System.currentTimeMillis();
}
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
setConnection(cookie, connection);
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
return connection;
}
private static void setConnection(String cookie, HttpURLConnection connection) {
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
connection.setRequestProperty("Cache-Control", "max-age=0");
connection.setRequestProperty("Referer", ".bilibili.com");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("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");
if (jsonObject == null) {
jsonObject = new JSONObject();
jsonObject.put("code", "-1");
jsonObject.put("data", new JSONObject());
}
return jsonObject;
}
}

View File

@ -0,0 +1,73 @@
package com.yutou.qqbot.bilibili;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.utlis.ConfigTools;
import com.yutou.qqbot.utlis.HttpTools;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class BiliLogin {
public JSONObject login(){
JSONObject login= JSONObject.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;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if((System.currentTimeMillis()-time)>5*60*1000){
cancel();
return;
}
JSONObject json=JSONObject.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<String,String> map=HttpTools.getUrlParams(_url);
JSONObject cookie=new JSONObject();
JSONArray array=new JSONArray();
for (String key : map.keySet()) {
cookie.put(key,map.get(key));
}
System.out.println(array);
JSONObject tmp=BiliBiliUtils.http_post(_url,"");
System.out.println("tmp = " + tmp);
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());
cancel();
}
}
},0,3000);
}
public boolean testLogin(){
JSONObject jsonObject = BiliBiliUtils.getLoginInfo();
return jsonObject.getInteger("code")==0;
}
public static void main(String[] args) {
BiliLogin login = new BiliLogin();
login.testLogin();
}
}

View File

@ -44,6 +44,7 @@ public abstract class Model implements ModelInterface {
public static final String ROUTER_ADD = "!添加设备"; public static final String ROUTER_ADD = "!添加设备";
public static final String ROUTER_DEL = "!删除设备"; public static final String ROUTER_DEL = "!删除设备";
public static final String BT_DOWNLOAD = "下载bt"; public static final String BT_DOWNLOAD = "下载bt";
public static final String BILI_MANGA_SIGN="!B站漫画签到";
} }

View File

@ -0,0 +1,60 @@
package com.yutou.qqbot.models.WebSign;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.bilibili.BiliBiliManga;
import com.yutou.qqbot.bilibili.BiliLogin;
import com.yutou.qqbot.models.Model;
import com.yutou.qqbot.utlis.QRCodeUtils;
import net.mamoe.mirai.event.events.MessageEvent;
import java.io.File;
public class BiliBiliMangeSign extends Model {
@Override
public boolean isUserPublic() {
return false;
}
@Override
public String[] getUsePowers() {
return new String[]{
QQFromCommands.BILI_MANGA_SIGN
};
}
@Override
public void onMessage(Long qq, MessageEvent event, boolean isGroup) {
super.onMessage(qq, event, isGroup);
if(event.getMessage().contentToString().equals(QQFromCommands.BILI_MANGA_SIGN)){
String msg;
if(new BiliLogin().testLogin()){
if(BiliBiliManga.sign()==null){
msg="B站漫画已经签到过了";
}else{
msg="B站漫画签到完成";
}
QQBotManager.getInstance().sendMessage(qq,msg);
}else{
String url = new BiliLogin().login().getString("url");
File code = QRCodeUtils.createQRCode("bili_login",url);
QQBotManager.getInstance().sendMessage(code,qq,"B站未登录,请扫码登陆后再试");
}
}
}
@Override
public void onTime(String time) {
super.onTime(time);
if("00:01:00".equals(time)){
if(new BiliLogin().testLogin()){
String msg;
if(BiliBiliManga.sign()==null){
msg="B站漫画已经签到过了";
}else{
msg="B站漫画签到完成";
}
QQBotManager.getInstance().sendMessage(msg);
}
}
}
}

View File

@ -11,6 +11,7 @@ public class ConfigTools {
public static final String CONFIG = "config.json"; public static final String CONFIG = "config.json";
public static final String DATA = "data.json"; public static final String DATA = "data.json";
public static final String SQLITE = "sqlite.json"; public static final String SQLITE = "sqlite.json";
public static final String BiliBili = "bilibili.cookie";
static { static {
try { try {
@ -104,7 +105,7 @@ public class ConfigTools {
String tmp; String tmp;
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
while ((tmp = reader.readLine()) != null) { while ((tmp = reader.readLine()) != null) {
str.append(tmp); str.append(tmp).append("\n");
} }
reader.close(); reader.close();
return str.toString(); return str.toString();

View File

@ -7,6 +7,8 @@ import org.jetbrains.annotations.NotNull;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -89,11 +91,13 @@ public class HttpTools {
//connection.addRequestProperty("User-Agent", getExtUa()); //connection.addRequestProperty("User-Agent", getExtUa());
//connection.addRequestProperty("content-type", "application/json"); //connection.addRequestProperty("content-type", "application/json");
connection.addRequestProperty("charset", "UTF-8"); connection.addRequestProperty("charset", "UTF-8");
OutputStream outputStream = connection.getOutputStream(); if(body!=null) {
//System.out.println(new String(body)); OutputStream outputStream = connection.getOutputStream();
outputStream.write(body); //System.out.println(new String(body));
outputStream.flush(); outputStream.write(body);
outputStream.close(); outputStream.flush();
outputStream.close();
}
connection.connect(); connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((tmp = reader.readLine()) != null) { while ((tmp = reader.readLine()) != null) {
@ -124,11 +128,11 @@ public class HttpTools {
Set<String> keys = json.keySet(); Set<String> keys = json.keySet();
for (String key : keys) { for (String key : keys) {
try { try {
string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8")); string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), StandardCharsets.UTF_8));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
try { try {
string.append("&").append(URLEncoder.encode(key, "UTF-8")).append("="); string.append("&").append(URLEncoder.encode(key, StandardCharsets.UTF_8)).append("=");
// string += "&" + key + "="; // string += "&" + key + "=";
} catch (Exception e1) { } catch (Exception e1) {
string.append("&").append(key).append("="); string.append("&").append(key).append("=");
@ -139,6 +143,17 @@ public class HttpTools {
string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", "")); string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
return string.toString(); return string.toString();
} }
public static Map<String,String> getUrlParams(String url){
Map<String,String> map=new HashMap<>();
if(url.contains("?")){
String param=url.split("\\?")[1];
String[] params=param.split("&");
for (String par : params) {
map.put(par.split("=")[0],par.split("=")[1]);
}
}
return map;
}
public static void main(String[] args) { public static void main(String[] args) {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();

View File

@ -0,0 +1,58 @@
package com.yutou.qqbot.utlis;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class QRCodeUtils {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
public static File createQRCode(String codeName,String value){
try {
String imageType = "jpg";// 图片类型
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(value, BarcodeFormat.QR_CODE, 400, 400, hints);
if(!new File("QRCode").exists()){
boolean mkdirs = new File(("QRCode")).mkdirs();
System.out.println("create QRCode dir is = "+mkdirs);
}
File file1 = new File("QRCode"+File.separator+ codeName + "." + imageType);
writeToFile(bitMatrix, imageType, file1);
return file1;
} catch (WriterException | IOException e) {
e.printStackTrace();
}
return null;
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
}

View File

@ -49,21 +49,24 @@ public class WebClient {
json.getString("domain"), json.getString("domain"),
json.getString("path"), json.getString("path"),
containsDate ? new Date(t) : new Date(), containsDate ? new Date(t) : new Date(),
json.getBoolean("secure"), json.containsKey("secure")?json.getBoolean("secure"):false,
json.getBoolean("httpOnly") json.containsKey("httpOnly")?json.getBoolean("httpOnly"):false
); );
list.add(cookie); list.add(cookie);
} }
return list; return list;
} }
static boolean headless=false;
public static void setHeadless(boolean headless){
WebClient.headless=headless;
}
public static ChromeOptions getOptions() { public static ChromeOptions getOptions() {
ChromeOptions options = new ChromeOptions(); ChromeOptions options = new ChromeOptions();
// options.addArguments("--disable-gpu"); // options.addArguments("--disable-gpu");
// options.addArguments("blink-settings=imagesEnabled=false"); // options.addArguments("blink-settings=imagesEnabled=false");
String headless = RedisTools.get("headless"); String headless = RedisTools.get("headless");
if("true".equals(headless)) { if("true".equals(headless)||WebClient.headless) {
options.addArguments("--headless"); options.addArguments("--headless");
} }
options.addArguments("--no-sandbox"); options.addArguments("--no-sandbox");