add 新增了批量订阅 add

This commit is contained in:
zlzw 2024-11-21 18:29:19 +08:00
parent b15d1c917f
commit 35b014c585
39 changed files with 1871 additions and 280 deletions

BIN
Web/assets/def.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

View File

@ -9,6 +9,7 @@
<body>
<div id="header"></div>
不想做了,鸽
</body>
<script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script>

View File

@ -89,6 +89,9 @@
]],
done: function () {
done();
if (getParam('type') === 'createRoom') {
createRoom('')
}
},
error: function (res, msg) {
console.log(res, msg)

View File

@ -23,7 +23,8 @@
</script>
<script type="text/html" id="toolDemo">
<div class="layui-clear-space">
<a class="layui-btn layui-btn-xs" lay-event="edit">删除</a>
<a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
<a class="layui-btn layui-btn-xs" lay-event="input">导入关注</a>
</div>
</script>
<script>
@ -39,8 +40,12 @@
});
}
function refreshCookie(data) {
console.log(data)
function refresh(data) {
refreshCookie(data)
.then(data => {
console.log(data)
layer.msg(data.message)
})
}
function createRoom() {
login()
@ -54,9 +59,10 @@
shadeClose: false, // 点击遮罩区域,关闭弹层
maxmin: true, // 允许全屏最小化
anim: 1, // 0-6 的动画形式,-1 不开启
content: '<div style="padding: 32px;text-align: center;" id="qrdiv">登陆后刷新</div>',
content: '<div style="padding: 32px;text-align: center;" id="qrdiv"><span id="loginTip">登陆后刷新</span></div>',
success: function (layero, index, that) {
new QRCode(document.getElementById("qrdiv"), data.data.qrcode);
reloadLogin(document.getElementById("loginTip"))
}
});
} else if (data.status === 301) {
@ -67,6 +73,17 @@
})
}
function reloadLogin(tips) {
setTimeout(() => {
login()
.then(data => {
tips.innerHTML = data.message;
if (data.code !== 302) {
reloadLogin(tips)
}
})
}, 1000);
}
</script>
<script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script>
@ -105,20 +122,56 @@
{ field: 'uid', title: 'UID', width: 150, sort: true, fixed: 'left', templet: '<div><a href="https://space.bilibili.com/{{= d.uid}}" target="_blank">{{= d.uid}}</a>' },
{ field: 'uname', title: '用户名', width: 150, fixed: 'left' },
{ field: 'face', title: '头像', width: 80, templet: '<div><image src="" onerror="showImage(\'{{= d.face }}\',this);" style="width: 30px;height: 30px;"></div>' },
{ field: 'status', title: '状态', width: 150, templet: '<div> {{= d.status}} <button class="layui-btn layui-btn-xs" onclick="refreshCookie(\'{{= d.uid }}\')">刷新cookie</button>' },
{ field: 'status', title: '状态', width: 150, templet: '<div> {{= d.status}} <button class="layui-btn layui-btn-xs" onclick="refresh(\'{{= d.uid }}\')">刷新cookie</button>' },
{ field: 'sql_time', title: '添加时间', width: 190 },
{ fixed: "right", title: "操作", width: 80, align: "center", toolbar: "#toolDemo" }
{ fixed: "right", title: "操作", width: 180, align: "center", toolbar: "#toolDemo" }
]],
done: function () {
onDone();
},
error: function (res, msg) {
console.log(res, msg)
}
});
function onDone() {
table.on('tool(roomTable)', function (obj) {
var id = obj.config.id;
var data = obj.data;
var checkStatus = table.checkStatus(id);
var othis = lay(this);
switch (obj.event) {
case 'input':
onClickInput(data.uid)
break;
};
});
}
function onClickInput(uid) {
layer.open({
type: 2, // page 层类型
area: ['650px', '400px'],
title: '选择主播',
shade: 0.6, // 遮罩透明度
shadeClose: false, // 点击遮罩区域,关闭弹层
maxmin: true, // 允许全屏最小化
anim: 1, // 0-6 的动画形式,-1 不开启
// btn: ['确定', '取消'],
content: '/html/ui/userFollow.html?uid=' + uid,
yes: function (index, layero) {
var iframeWin = window[layero.find('iframe')[0]['name']];
var anchorRoomId = iframeWin.$('#anchorRoomId')[0].value;
if (!hasString(anchorRoomId)) {
layer.msg("请选择")
return
}
let url = new URL(window.location.href);
url.searchParams.set('roomId', anchorRoomId);
window.location.href = url.toString();
}
});
}
});

View File

@ -46,8 +46,14 @@
&nbsp; <div id="slider" lay-options="{value: 100,input:true}"></div>
<span>弹幕透明度</span>
</div>
</div>
<div class="layui-row">
<div class="layui-col-xs2">&nbsp;</div>
<div class="layui-col-xs7">
<canvas id="giftChart" height="200"></canvas>
</div>
</div>
<div style="margin-bottom: 10vh;"></div>
</body>
<script id="menulist" type="text/html">
<ul class="layui-tab-title">
@ -106,7 +112,7 @@
<script src="/js/hls.js"></script>
<script src="/js/fly-barrage.iife.js"></script>
<script src="/js/lodash.min.js"></script>
<script src="/js/Chart.min.js"></script>
<script>
headerModel = 2;
@ -221,9 +227,49 @@
playVideo(data.data)
}, 300)
})
});
initChart(roomId, options.id)
});
function initChart(roomId, videoId) {
getVideoGiftInfo(roomId, videoId)
.then(data => {
if (data.status != 100) {
return
}
var lables = [];
var values = [];
data.data.guardInfo.forEach(item => {
lables.push(item.gift_name+"\n"+item.total_price/100+"¥")
values.push(item.total_num)
});
data.data.giftInfo.forEach(item => {
lables.push(item.gift_name+"\n"+item.total_price/100+"¥")
values.push(item.total_gift_num)
});
new Chart($('#giftChart').get(0), {
type: 'bar',
data: {
labels: lables,
datasets: [{
label: '礼物(总额:'+data.data.price/100+"¥)",
data: values,
borderWidth: 1
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
})
}
function initMenu(data) {
var view = $("#menuView").get(0);
laytpl($('#menulist').get(0).innerHTML).render(data, function (html) {
@ -244,7 +290,7 @@
layer.open({
type: 2, // page 层类型
area: ['320px', '400px'],
title: '打开B站客户端扫码登陆',
title: '选择主播',
shade: 0.6, // 遮罩透明度
shadeClose: false, // 点击遮罩区域,关闭弹层
maxmin: true, // 允许全屏最小化

133
Web/html/ui/userFollow.html Normal file
View File

@ -0,0 +1,133 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/layui/css/layui.css">
</head>
<table class="layui-hide" id="followList" lay-filter="followTable"></table>
<body>
</body>
<script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script>
<script src="/js/CommonConfig.js"></script>
<script src="/js/httpUtils.js"></script>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" onclick="addAll()">一键配置全部</button>
<button class="layui-btn layui-btn-sm" lay-event="select">配置选择项</button>
</div>
</script>
<script type="text/html" id="toolDemo">
<div class="layui-clear-space">
<a class="layui-btn layui-btn-xs" lay-event="add">添加</a>
</div>
</script>
<script>
var userId = getParam("uid");
function addAll() {
addAllFollow(userId)
.then(data => {
layer.msg(data.message)
})
}
layui.use(function () {
var laytpl = layui.laytpl;
var table = layui.table;
table.render({
elem: '#followList',
url: '/live/config/follow?userId=' + userId,
toolbar: '#toolbarDemo',
height: '350px',
totalRow: true, // 开启合计行
page: true,
response: {
statusCode: 100 // 重新规定成功的状态码为 200table 组件默认为 0
},
parseData: function (res) {
return {
"code": res.status, //解析接口状态
"msg": res.message, //解析提示文本
"data": res.data.list, //解析数据列表
"count": res.count
};
},
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'mid', title: 'UID', width: 150, sort: true, fixed: 'left', templet: '<div><a href="https://space.bilibili.com/{{= d.mid}}" target="_blank">{{= d.mid}}</a>' },
{ field: 'uname', title: '用户名', width: 150, fixed: 'left' },
{ field: 'face', title: '头像', width: 80, templet: '<div><image src="" onerror="showImage(\'{{= d.face }}\',this);" style="width: 30px;height: 30px;"></div>' },
{ field: 'mtime', title: '关注时间', width: 150, templet: '<div> {{= formatDate(d.mtime*1000)}} </div>' },
{ fixed: "right", title: "操作", width: 50, align: "center", toolbar: "#toolDemo" }
]],
done: function () {
onDone()
},
error: function (res, msg) {
console.log(res, msg)
}
});
function onDone() {
table.on('toolbar(followTable)', function (obj) {
if (obj.event === 'select') {
var data = table.checkStatus(obj.config.id).data;
console.log(data)
var array=[]
data.forEach(item => {
array.push({
"mid":item.mid,
"uname":item.uname
})
});
addFollowList(userId,JSON.stringify(array))
.then(json=>{
layer.msg(json.message)
})
}
})
table.on('tool(followTable)', function (obj) {
if (obj.event === 'add') {
var loadIndex = layer.msg('配置中', {
icon: 16,
shade: 0.6
});;
addFollow(userId, obj.data.mid)
.then(data => {
layer.close(loadIndex)
if (data.status === 3) {
openTips(data.message,obj.data.mid)
} else {
layer.msg(data.message)
}
})
}
})
}
function openTips(message,mid) {
layer.alert(message, {
title: "提示",
btn: ['打开配置页', '前往UP主页', '取消'],
btnAlign: 'c', // 按钮居中显示
btn1: function () {
window.open("/html/body/live.html?type=createRoom" , '_blank')
},
btn2: function () {
window.open("https://space.bilibili.com/" + mid, '_blank')
},
btn3: function () {
}
});
}
})
</script>

View File

@ -11,12 +11,38 @@
<body>
<div id="header"></div>
<div class="layui-row layui-col-space15">
<div id="follow">
</div>
<div id="card"></div>
</div><br>
<div id="page"></div>
</body>
<script id="followStatus" type="text/html">
{{# layui.each(d.data, function(index, item){ }}
{{# if(item.status !== -1) { }}
{{# var color = item.status === -100 ? "#16b777" : "#ffb800"; }}
{{# var icon = item.status === -100 ? "layui-icon-ok-circle" : "layui-icon-flag"; }}
{{# var isOver = item.status === -100; }}
<blockquote class="layui-elem-quote" style="border-left: 5px solid {{= color}}; margin-left: 5dvw; margin-top: 5dvh; margin-right: 5dvw;">
<i class="layui-icon {{= icon }}" style="font-size: 20px; color: {{= color}};"></i>
<span style="font-size: 16px;" id="{{= item.data}}">
{{= item.message}}
</span>
{{# if(isOver) { }}
<span style="float: right;">
<button type="button" class="layui-btn layui-btn-sm" onclick="confirmFollow({{= item.data}})">确认</button>
</span>
{{# } else { }}
<span style="float: right;">
<button type="button" class="layui-btn layui-btn-sm layui-bg-orange" onclick="confirmFollow({{= item.data}})">取消</button>
</span>
{{# } }}
</blockquote>
{{# } }}
{{# }); }}
</script>
<script id="liveCard" type="text/html">
{{# layui.each(d.data, function(index, item){ }}
<div class="layui-col-xs3 layui-col-sm3 layui-col-md3">
@ -33,20 +59,21 @@
</span>
</div>
<div class="layui-card-body">
<img src="#" onerror="showTmpImage('{{= item.cover}}',this)" onclick="toLive('{{= item.roomId}}')" style="width: 100%; height: 100%;"/><br>
<img src="#" onerror="showTmpImage('{{= item.cover}}',this)" onclick="toLive('{{= item.roomId}}')" style="width: 312px; height: 175px; object-fit: cover;"/><br>
<!-- <img src="#" onerror="showImage('{{= item.cover}}',this)" onclick="toLive('{{= item.roomId}}')" style="width: 100%; height: 100%;"/><br> -->
{{= item.title}}<br>
<p>开播时长:{{= item.liveTime}}</p>
直播录制状态:
{{# if(item.downloadVideo){ }}
<span style="color: #16b777" onclick="clickVideo('{{= item.roomId}}',true)">录制中</span>
{{# } else{ }}
<span style="color: #FD482C" onclick="clickVideo('{{= item.roomId}}',false)">监听</span>
<span style="color: #FD482C" onclick="clickVideo('{{= item.roomId}}',false)">待机</span>
{{# }; }}<br>
弹幕录制状态:
{{# if(item.danmu){ }}
<span style="color: #16b777" onclick="clickDanmu('{{= item.roomId}}',true)">录制中</span>
{{# } else{ }}
<span style="color: #FD482C" onclick="clickDanmu('{{= item.roomId}}',false)">监听</span>
<span style="color: #FD482C" onclick="clickDanmu('{{= item.roomId}}',false)">待机</span>
{{# }; }}<br>
</div>
</div>
@ -64,9 +91,9 @@
<script>
headerModel = 0;
$('#header').load("/html/header.html");
function toLive(roomId){
function toLive(roomId) {
console.log(roomId)
window.open("https://live.bilibili.com/"+roomId,'_blank')
window.open("https://live.bilibili.com/" + roomId, '_blank')
}
function clickVideo(roomId, status) {
const title = "是否" + (status ? "停止" : "启动") + "录制视频?"
@ -114,6 +141,12 @@
layer.msg('点击取消的回调');
});
}
function confirmFollow(userId) {
confirmFollowStatus(userId)
.then(data => {
layer.msg(data.message)
})
}
</script>
<script>
layui.use(['laytpl', 'laypage'], function () {
@ -121,9 +154,9 @@
var laypage = layui.laypage;
var pageIndex = 1;
var pageMax = 16;
var listCount=10;
var listMax=pageMax;
var initPage=true;
var listCount = 10;
var listMax = pageMax;
var initPage = true;
function initCard() {
var loadIndex = layer.msg('加载中', {
icon: 16,
@ -131,9 +164,9 @@
});
getAllLive(pageIndex, pageMax)
.then(data => {
listCount=data.count;
if(initPage){
initPage=false;
listCount = data.count;
if (initPage) {
initPage = false;
initPageView();
}
var view = $("#card").get(0);
@ -141,29 +174,53 @@
view.innerHTML = html;
layer.close(loadIndex)
});
})
}
function initFollowStatus(init) {
checkFollowStatus('')
.then(data => {
var tmp = -1;
data.data.forEach(element => {
tmp = element.status;
});
if (tmp === -1) {
return
}
if (init) {
var view = $("#follow").get(0);
laytpl($('#followStatus').get(0).innerHTML).render(data, function (html) {
view.innerHTML = html;
});
}
setTimeout(() => {
initFollowStatus(true)
}, 1000);
})
}
function init() {
initCard()
initCard();
initFollowStatus(true);
}
function initPageView(){
function initPageView() {
laypage.render({
elem: 'page',
limit: 16,
curr: pageIndex,
limits: [4, 8, 16, 24, 32, 40],
layout: ['prev', 'page', 'next', 'limit'],
count: listCount, // 数据总数
jump: function (obj, first) {
listMax=obj.limit
if (!first) {
pageIndex =obj.curr;
pageMax = obj.limit;
initCard()
}
}
});
elem: 'page',
limit: 16,
curr: pageIndex,
limits: [4, 8, 16, 24, 32, 40],
layout: ['prev', 'page', 'next', 'limit'],
count: listCount, // 数据总数
jump: function (obj, first) {
listMax = obj.limit
if (!first) {
pageIndex = obj.curr;
pageMax = obj.limit;
initCard()
}
}
});
}
init()
})

19
Web/js/Chart.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -17,6 +17,7 @@ function getParam(name){
}
}
function showImage(url, imgElement) {
getHttpImage(url)
.then(imageUrl => {
imgElement.src = imageUrl;
@ -27,6 +28,11 @@ function showImage(url, imgElement) {
});
}
function showTmpImage(url, imgElement) {
console.log(url)
if(!hasString(url)){
imgElement.src='/assets/def.png'
return
}
getHttpTmpImage(url)
.then(blob => {
imgElement.src ="data:image/jpeg;base64,"+blob;
@ -38,4 +44,17 @@ function showTmpImage(url, imgElement) {
}
function hasString(text){
return !!text;
}
function formatDate(timestamp) {
const date = new Date(timestamp);
const padZero = (num) => (num < 10 ? '0' + num : num);
const year = date.getFullYear();
const month = padZero(date.getMonth() + 1);
const day = padZero(date.getDate());
const hours = padZero(date.getHours());
const minutes = padZero(date.getMinutes());
const seconds = padZero(date.getSeconds());
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

View File

@ -112,7 +112,23 @@ function getRoomConfig(roomId){
function deleteRoomConfig(roomId){
return get("/live/config/delete?roomId="+roomId)
}
function checkFollowStatus(userId){
return get("/live/config/follow/check?userId="+userId)
}
function confirmFollowStatus(userId){
return get("/live/config/follow/confirm?userId="+userId)
}
function addAllFollow(userId){
return get("/live/config/follow/all?userId="+userId)
}
function addFollow(uid,anchorId){
return get("/live/config/follow/add?anchorId="+anchorId+"&uid="+uid)
}
function addFollowList(uid,array){
const formData = new FormData();
formData.append("array", array);
return post("/live/config/follow/addList?uid="+uid,formData,true)
}
//----------------直播配置相关接口end
//----------------首页相关接口
function getAllLive(page,limit){
@ -154,4 +170,12 @@ function getBiliAllUser(){
function login(){
return get("/user/login")
}
//----------------用户相关接口end
function refreshCookie(userId){
return get("/user/refreshCookie?uid="+userId)
}
//----------------用户相关接口end
//----------------礼物相关接口
function getVideoGiftInfo(roomId,videoId){
return get("/live/gift/info?roomId="+roomId+"&videoId="+videoId)
}
//----------------礼物相关接口end

View File

@ -1,18 +1,15 @@
package com.yutou.biliapi;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.UserApi;
import com.yutou.biliapi.bean.live.SpiBean;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.login.UserInfoBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.biliapi.net.BiliLoginNetApiManager;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliUserNetApiManager;
import com.yutou.common.inter.IHttpApiCheckCallback;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.okhttp.HttpCallback;
import com.yutou.common.okhttp.HttpLoggingInterceptor;
import com.yutou.common.utils.Log;
import jakarta.xml.bind.DatatypeConverter;
import okhttp3.Headers;
@ -21,8 +18,6 @@ import retrofit2.Response;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {

View File

@ -6,9 +6,7 @@ import com.yutou.biliapi.bean.login.QRCodeGenerateBean;
import com.yutou.common.okhttp.FileBody;
import com.yutou.common.okhttp.HttpBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.*;
public interface LoginApi {
/**
@ -32,10 +30,11 @@ public interface LoginApi {
@GET("https://www.bilibili.com/correspond/1/{correspondPath}")
Call<FileBody<String>> getCorrespond(@Path("correspondPath") String correspondPath);
@GET("/x/passport-login/web/cookie/refresh")
Call<HttpBody<LoginInfoBean>> refreshCookie(@Query("csrf") String bili_jct
, @Query("refresh_csrf") String refresh_csrf
, @Query("source") String source
, @Query("refresh_token") String refresh_token
@POST("/x/passport-login/web/cookie/refresh")
@FormUrlEncoded
Call<HttpBody<LoginInfoBean>> refreshCookie(@Field("csrf") String bili_jct
, @Field("refresh_csrf") String refresh_csrf
, @Field("source") String source
, @Field("refresh_token") String refresh_token
);
}

View File

@ -1,10 +1,19 @@
package com.yutou.biliapi.api;
import com.yutou.biliapi.bean.live.SpiBean;
import com.yutou.biliapi.bean.login.UserInfoBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.biliapi.bean.user.UserHomeInfoBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.common.okhttp.BaseBean;
import com.yutou.common.okhttp.HttpBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import java.util.List;
import java.util.TreeMap;
public interface UserApi {
@GET("/x/web-interface/nav")
@ -13,4 +22,18 @@ public interface UserApi {
@GET("/x/frontend/finger/spi")
Call<HttpBody<SpiBean>> getFingerSpi();
@GET("/x/relation/followings")
Call<HttpBody<UserFollowingsBean>> getFollowings(
@Query("vmid") String uid,
@Query("order_type") String type,
@Query("ps") int num,
@Query("pn") int page
);
@GET("/x/space/wbi/acc/info")
Call<HttpBody<UserHomeInfoBean>> getWbiAccInfo(
@QueryMap TreeMap<String,Object> param
);
}

View File

@ -15,10 +15,7 @@ import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.*;
import static com.alibaba.fastjson2.util.DateUtils.DateTimeFormatPattern.DATE_FORMAT_10_DASH;
@ -40,7 +37,7 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
@JSONField(name = "keyword")
private List<String> keywordList;
@JSONField(name = "weeks")
private List<String> weeks;
private List<String> weeks=Arrays.asList("1","2","3","4","5","6","7");
@JSONField(name = "recordPath")
private String recordPath = "live";
@JSONField(name = "recordUid")
@ -48,9 +45,9 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
@JSONField(name = "recordLiveModel")
private int recordLiveModel;//0 - ffmpeg 1 - java
@JSONField(name = "recordDanmuDate")
private String recordDanmuDate = null;// 时间范围 20:00:00 - 23:59:59
private String recordDanmuDate = "00:00:00 - 23:59:59";// 时间范围 20:00:00 - 23:59:59
@JSONField(name = "recordLiveDate")
private String recordLiveDate = null;// 时间范围 20:00:00 - 23:59:59
private String recordLiveDate = "00:00:00 - 23:59:59";// 时间范围 20:00:00 - 23:59:59
public LiveConfigDatabaseBean() {
@ -58,11 +55,11 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
}
public boolean checkRecordDanmuTime() {
return DateFormatUtils.checkTime(weeks,recordDanmuDate);
return DateFormatUtils.getInstance().checkTime(weeks,recordDanmuDate);
}
public boolean checkRecordLiveTime() {
return DateFormatUtils.checkTime(weeks,recordLiveDate);
return DateFormatUtils.getInstance().checkTime(weeks,recordLiveDate);
}
public boolean verifyDanmuTimer() {
@ -76,8 +73,8 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
private boolean verifyTimer(String val) {
try {
String[] time = val.split(" - ");
Date start = DateFormatUtils.parseTimer(time[0]);
Date end = DateFormatUtils.parseTimer(time[1]);
Date start = DateFormatUtils.getInstance().parseTimer(time[0]);
Date end = DateFormatUtils.getInstance().parseTimer(time[1]);
if (start != null && end != null) {
return true;
}
@ -94,6 +91,6 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
List<String> weeks = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
LiveConfigDatabaseBean bean=new LiveConfigDatabaseBean();
bean.setWeeks(weeks);
System.out.println(DateFormatUtils.checkTime(weeks,t));
System.out.println(DateFormatUtils.getInstance().checkTime(weeks,t));
}
}

View File

@ -1,8 +1,8 @@
package com.yutou.biliapi.bean.login;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.alibaba.fastjson2.util.DateUtils;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.common.databases.AbsDatabasesBean;
import lombok.Data;
import lombok.EqualsAndHashCode;

View File

@ -0,0 +1,143 @@
package com.yutou.biliapi.bean.user;
import com.alibaba.fastjson2.annotation.JSONField;
import com.yutou.common.okhttp.BaseBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
public class UserFollowingsBean extends BaseBean {
@JSONField(name = "list")
private List<Follow> list;
@JSONField(name = "total")
private int total;
@Data
public static class Follow{
@JSONField(name = "mid")
private String mid;
@JSONField(name = "attribute")
private int attribute;
@JSONField(name = "mtime")
private long mtime;
@JSONField(name = "tag")
private Object tag; // 可能为 null
@JSONField(name = "special")
private int special;
@JSONField(name = "contract_info")
private Object contractInfo; // 可能为一个空对象 {}
@JSONField(name = "uname")
private String uname;
@JSONField(name = "face")
private String face;
@JSONField(name = "sign")
private String sign;
@JSONField(name = "face_nft")
private int faceNft;
@JSONField(name = "official_verify")
private OfficialVerify officialVerify;
@JSONField(name = "vip")
private Vip vip;
@JSONField(name = "name_render")
private Object nameRender; // 可能为一个空对象 {}
@JSONField(name = "nft_icon")
private String nftIcon;
@JSONField(name = "rec_reason")
private String recReason;
@JSONField(name = "track_id")
private String trackId;
@JSONField(name = "follow_time")
private String followTime;
}
@Data
public static class OfficialVerify {
@JSONField(name = "type")
private int type;
@JSONField(name = "desc")
private String desc;
}
@Data
public static class Vip {
@JSONField(name = "vipType")
private int vipType;
@JSONField(name = "vipDueDate")
private long vipDueDate;
@JSONField(name = "dueRemark")
private String dueRemark;
@JSONField(name = "accessStatus")
private int accessStatus;
@JSONField(name = "vipStatus")
private int vipStatus;
@JSONField(name = "vipStatusWarn")
private String vipStatusWarn;
@JSONField(name = "themeType")
private int themeType;
@JSONField(name = "label")
private Label label;
@JSONField(name = "avatar_subscript")
private int avatarSubscript;
@JSONField(name = "nickname_color")
private String nicknameColor;
@JSONField(name = "avatar_subscript_url")
private String avatarSubscriptUrl;
}
@Data
public static class Label {
@JSONField(name = "path")
private String path;
@JSONField(name = "text")
private String text;
@JSONField(name = "label_theme")
private String labelTheme;
@JSONField(name = "text_color")
private String textColor;
@JSONField(name = "bg_style")
private int bgStyle;
@JSONField(name = "bg_color")
private String bgColor;
@JSONField(name = "border_color")
private String borderColor;
}
}

View File

@ -0,0 +1,495 @@
package com.yutou.biliapi.bean.user;
import com.alibaba.fastjson2.annotation.JSONField;
import com.yutou.common.okhttp.BaseBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
public class UserHomeInfoBean extends BaseBean {
@JSONField(name = "mid")
private long mid;
@JSONField(name = "name")
private String name;
@JSONField(name = "sex")
private String sex;
@JSONField(name = "face")
private String face;
@JSONField(name = "face_nft")
private long faceNft;
@JSONField(name = "face_nft_type")
private long faceNftType;
@JSONField(name = "sign")
private String sign;
@JSONField(name = "rank")
private long rank;
@JSONField(name = "level")
private long level;
@JSONField(name = "jointime")
private long jointime;
@JSONField(name = "moral")
private long moral;
@JSONField(name = "silence")
private long silence;
@JSONField(name = "coins")
private long coins;
@JSONField(name = "fans_badge")
private boolean fansBadge;
@JSONField(name = "fans_medal")
private FansMedal fansMedal;
@JSONField(name = "official")
private Official official;
@JSONField(name = "vip")
private Vip vip;
@JSONField(name = "pendant")
private Pendant pendant;
@JSONField(name = "nameplate")
private Nameplate nameplate;
@JSONField(name = "user_honour_info")
private UserHonourInfo userHonourInfo;
@JSONField(name = "is_followed")
private boolean isFollowed;
@JSONField(name = "top_photo")
private String topPhoto;
@JSONField(name = "theme")
private SysNotice theme;
@JSONField(name = "sys_notice")
private SysNotice sysNotice;
@JSONField(name = "live_room")
private LiveRoom liveRoom;
@JSONField(name = "birthday")
private String birthday;
@JSONField(name = "school")
private Object school;
@JSONField(name = "profession")
private Profession profession;
@JSONField(name = "tags")
private List<String> tags;
@JSONField(name = "series")
private Series series;
@JSONField(name = "is_senior_member")
private long isSeniorMember;
@JSONField(name = "mcn_info")
private Object mcnInfo;
@JSONField(name = "gaia_res_type")
private long gaiaResType;
@JSONField(name = "gaia_data")
private Object gaiaData;
@JSONField(name = "is_risk")
private boolean isRisk;
@JSONField(name = "elec")
private Elec elec;
@JSONField(name = "contract")
private Object contract;
@JSONField(name = "certificate_show")
private boolean certificateShow;
@JSONField(name = "name_render")
private Object nameRender;
@Data
public static class Elec {
@JSONField(name = "show_info")
private ShowInfo showInfo;
}
@Data
public static class ShowInfo {
@JSONField(name = "show")
private boolean show;
@JSONField(name = "state")
private long state;
@JSONField(name = "title")
private String title;
@JSONField(name = "icon")
private String icon;
@JSONField(name = "jump_url")
private String jumpURL;
}
@Data
public static class FansMedal {
@JSONField(name = "show")
private boolean show;
@JSONField(name = "wear")
private boolean wear;
@JSONField(name = "medal")
private Medal medal;
}
@Data
public static class Medal {
@JSONField(name = "uid")
private long uid;
@JSONField(name = "target_id")
private long targetID;
@JSONField(name = "medal_id")
private long medalID;
@JSONField(name = "level")
private long level;
@JSONField(name = "medal_name")
private String medalName;
@JSONField(name = "medal_color")
private long medalColor;
@JSONField(name = "intimacy")
private long intimacy;
@JSONField(name = "next_intimacy")
private long nextIntimacy;
@JSONField(name = "day_limit")
private long dayLimit;
@JSONField(name = "today_feed")
private long todayFeed;
@JSONField(name = "medal_color_start")
private long medalColorStart;
@JSONField(name = "medal_color_end")
private long medalColorEnd;
@JSONField(name = "medal_color_border")
private long medalColorBorder;
@JSONField(name = "is_lighted")
private long isLighted;
@JSONField(name = "guard_level")
private long guardLevel;
@JSONField(name = "light_status")
private long lightStatus;
@JSONField(name = "wearing_status")
private long wearingStatus;
@JSONField(name = "score")
private long score;
}
@Data
public static class LiveRoom {
@JSONField(name = "roomStatus")
private long roomStatus;
@JSONField(name = "liveStatus")
private long liveStatus;
@JSONField(name = "url")
private String url;
@JSONField(name = "title")
private String title;
@JSONField(name = "cover")
private String cover;
@JSONField(name = "roomid")
private long roomid;
@JSONField(name = "roundStatus")
private long roundStatus;
@JSONField(name = "broadcast_type")
private long broadcastType;
@JSONField(name = "watched_show")
private WatchedShow watchedShow;
}
@Data
public static class WatchedShow {
@JSONField(name = "switch")
private boolean watchedShowSwitch;
@JSONField(name = "num")
private long num;
@JSONField(name = "text_small")
private String textSmall;
@JSONField(name = "text_large")
private String textLarge;
@JSONField(name = "icon")
private String icon;
@JSONField(name = "icon_location")
private String iconLocation;
@JSONField(name = "icon_web")
private String iconWeb;
}
@Data
public static class Nameplate {
@JSONField(name = "nid")
private long nid;
@JSONField(name = "name")
private String name;
@JSONField(name = "image")
private String image;
@JSONField(name = "image_small")
private String imageSmall;
@JSONField(name = "level")
private String level;
@JSONField(name = "condition")
private String condition;
}
@Data
public static class Official {
@JSONField(name = "role")
private long role;
@JSONField(name = "title")
private String title;
@JSONField(name = "desc")
private String desc;
@JSONField(name = "type")
private long type;
}
@Data
public static class Pendant {
@JSONField(name = "pid")
private long pid;
@JSONField(name = "name")
private String name;
@JSONField(name = "image")
private String image;
@JSONField(name = "expire")
private long expire;
@JSONField(name = "image_enhance")
private String imageEnhance;
@JSONField(name = "image_enhance_frame")
private String imageEnhanceFrame;
@JSONField(name = "n_pid")
private long nPID;
}
@Data
public static class Profession {
@JSONField(name = "name")
private String name;
@JSONField(name = "department")
private String department;
@JSONField(name = "title")
private String title;
@JSONField(name = "is_show")
private long isShow;
}
@Data
public static class Series {
@JSONField(name = "user_upgrade_status")
private long userUpgradeStatus;
@JSONField(name = "show_upgrade_window")
private boolean showUpgradeWindow;
}
@Data
public static class SysNotice {
}
@Data
public static class UserHonourInfo {
@JSONField(name = "mid")
private long mid;
@JSONField(name = "colour")
private Object colour;
@JSONField(name = "tags")
private List<Object> tags;
@JSONField(name = "is_latest_100honour")
private long isLatest100Honour;
}
@Data
public static class Vip {
@JSONField(name = "type")
private long type;
@JSONField(name = "status")
private long status;
@JSONField(name = "due_date")
private long dueDate;
@JSONField(name = "vip_pay_type")
private long vipPayType;
@JSONField(name = "theme_type")
private long themeType;
@JSONField(name = "label")
private Label label;
@JSONField(name = "avatar_subscript")
private long avatarSubscript;
@JSONField(name = "nickname_color")
private String nicknameColor;
@JSONField(name = "role")
private long role;
@JSONField(name = "avatar_subscript_url")
private String avatarSubscriptURL;
@JSONField(name = "tv_vip_status")
private long tvVipStatus;
@JSONField(name = "tv_vip_pay_type")
private long tvVipPayType;
@JSONField(name = "tv_due_date")
private long tvDueDate;
@JSONField(name = "avatar_icon")
private AvatarIcon avatarIcon;
}
@Data
public static class AvatarIcon {
@JSONField(name = "icon_type")
private long iconType;
@JSONField(name = "icon_resource")
private SysNotice iconResource;
}
@Data
public static class Label {
@JSONField(name = "path")
private String path;
@JSONField(name = "text")
private String text;
@JSONField(name = "label_theme")
private String labelTheme;
@JSONField(name = "text_color")
private String textColor;
@JSONField(name = "bg_style")
private long bgStyle;
@JSONField(name = "bg_color")
private String bgColor;
@JSONField(name = "border_color")
private String borderColor;
@JSONField(name = "use_img_label")
private boolean useImgLabel;
@JSONField(name = "img_label_uri_hans")
private String imgLabelURIHans;
@JSONField(name = "img_label_uri_hant")
private String imgLabelURIHant;
@JSONField(name = "img_label_uri_hans_static")
private String imgLabelURIHansStatic;
@JSONField(name = "img_label_uri_hant_static")
private String imgLabelURIHantStatic;
}
}

View File

@ -1,4 +1,4 @@
package com.yutou.biliapi.bean.login;
package com.yutou.biliapi.bean.user;
import com.alibaba.fastjson2.annotation.JSONField;
@ -6,7 +6,6 @@ import com.yutou.common.okhttp.BaseBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigInteger;
import java.util.Date;
@EqualsAndHashCode(callSuper = true)

View File

@ -4,11 +4,11 @@ import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.login.UserInfoBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.bilibili.Tools.DateFormatUtils;
import com.yutou.common.databases.AbsDatabasesBean;
import com.yutou.common.databases.SQLiteManager;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@ -86,7 +86,9 @@ public class BiliBiliLoginDatabase extends SQLiteManager {
List<LoginUserDatabaseBean> list = new ArrayList<>();
for (Object o : jsonArray) {
JSONObject json = (JSONObject) o;
list.add(new LoginUserDatabaseBean(json.to(UserInfoBean.class)));
LoginUserDatabaseBean bean = new LoginUserDatabaseBean(json.to(UserInfoBean.class));
bean.setSql_time(DateFormatUtils.getInstance().parse(json.getString("sql_time"),DateFormatUtils.DEFAULT_PATTERN));
list.add(bean);
}
return list;
}
@ -100,6 +102,10 @@ public class BiliBiliLoginDatabase extends SQLiteManager {
protected List<AbsDatabasesBean> getDataBean() {
return List.of(new LoginCookieDatabaseBean(), new LoginUserDatabaseBean(null));
}
public void updateLoginCookie(LoginCookieDatabaseBean cookie) {
update(cookie);
}
}
/**
*

View File

@ -1,5 +1,6 @@
package com.yutou.biliapi.databases;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.yutou.biliapi.bean.live.*;
@ -116,8 +117,67 @@ public class BiliLiveDatabase extends SQLiteManager {
addData(bean);
}
public JSONObject getGiftInfo(long startTimeLong, long endTimeLong) {
String startTime = DateFormatUtils.getInstance().format(startTimeLong);
String endTime = DateFormatUtils.getInstance().format(endTimeLong);
String giftSql = "WITH filtered_gifts AS (" +
"SELECT " +
"`gift_name`," +
"`icon`, " +
"SUM(`gift_num`) AS `total_gift_num`," +
"CASE " +
"WHEN `coin_type` = 'silver' THEN 0 " +
"ELSE SUM(`price` * `gift_num`) " +
"END AS `total_price`" +
"FROM " +
"`gift` " +
"WHERE " +
"`sql_time` >= '" + startTime + "' " +
"AND `sql_time` <= '" + endTime + "' " +
"GROUP BY " +
"`gift_name`, `coin_type`" +
")" +
"SELECT " +
"`gift_name`," +
"`icon`," +
"SUM(`total_gift_num`) AS `total_gift_num`," +
"SUM(`total_price`) AS `total_price`" +
"FROM " +
"filtered_gifts " +
"GROUP BY " +
"`gift_name`, `icon`;";
String guardSql = "SELECT `gift_name`, SUM(`num`) AS `total_num`,SUM(`price`*`num`) as `total_price`" +
"FROM `guardBuy` where `sql_time` >= '" + startTime + "' and `sql_time` <= '" + endTime + "'" +
"GROUP BY `gift_name`;";
String superChatSql = "SELECT SUM(`price`*100) as `total_price`, count(`price`) as `total_count`" +
"FROM `superChat` where `sql_time` >= '" + startTime + "' and `sql_time` <= '" + endTime + "';";
JSONObject json = new JSONObject();
JSONArray giftInfo = get(giftSql);
JSONArray guardInfo = get(guardSql);
JSONArray superChatInfo = get(superChatSql);
json.put("giftInfo", giftInfo);
json.put("guardInfo", guardInfo);
if (!superChatInfo.isEmpty()) {
json.put("superChatInfo", superChatInfo.getFirst());
} else {
json.put("superChatInfo", new JSONObject());
}
json.put("price", getGiftPrice(giftInfo) + getGiftPrice(guardInfo) + getGiftPrice(superChatInfo));
return json;
}
private long getGiftPrice(JSONArray array) {
long price = 0;
for (Object o : array) {
JSONObject item = (JSONObject) o;
price += item.getLongValue("total_price");
}
return price;
}
private void createInfo(LiveVideoDatabaseBean bean) {
String format = DateFormatUtils.format(bean.getSql_time());
String format = DateFormatUtils.getInstance().format(bean.getSql_time());
if (get(bean.getTableName(), " `sql_time` = '" + format + "'", LiveVideoDatabaseBean.class).isEmpty()) {
add(bean);
} else {
@ -125,18 +185,18 @@ public class BiliLiveDatabase extends SQLiteManager {
}
}
public <T extends AbsDatabasesBean> List<T> getOfTime(String startTime, String entTime, Class<T> clazz) {
public <T extends AbsDatabasesBean> List<T> getOfTime(String startTime, String endTime, Class<T> clazz) {
String tableName = null;
StringBuilder sb = new StringBuilder();
String where = null;
if (startTime != null) {
sb.append(" `sql_time` >= ").append("\"").append(startTime).append("\"");
}
if (entTime != null) {
if (endTime != null) {
if (!sb.isEmpty()) {
sb.append(" and ");
}
sb.append(" `sql_time` <= ").append("\"").append(entTime).append("\"");
sb.append(" `sql_time` <= ").append("\"").append(endTime).append("\"");
}
if (!sb.isEmpty()) {
where = sb.toString();
@ -150,6 +210,16 @@ public class BiliLiveDatabase extends SQLiteManager {
return super.get(tableName, where, clazz);
}
public LiveVideoDatabaseBean getVideo(String videoId) {
for (LiveVideoDatabaseBean info : getLiveInfos()) {
System.out.println(videoId + " " + info.getSql_time().getTime());
if (videoId.trim().equals(String.valueOf(info.getSql_time().getTime()))) {
return info;
}
}
return null;
}
public void resetSQL() {
List<AbsDatabasesBean> list = List.of(
new LiveInfoDatabaseBean(),
@ -175,7 +245,7 @@ public class BiliLiveDatabase extends SQLiteManager {
public static void main(String[] args) {
BiliLiveDatabase biliLiveDatabase = new BiliLiveDatabase(LiveRoomConfig.buildConfig("7688602"));
biliLiveDatabase.resetSQL();
biliLiveDatabase.resetSQL();
biliLiveDatabase.resetData();
}

View File

@ -3,22 +3,17 @@ package com.yutou.biliapi.net;
import com.yutou.biliapi.api.LoginApi;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginInfoBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.common.okhttp.FileBody;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.okhttp.HttpLoggingInterceptor;
import com.yutou.common.utils.Log;
import com.yutou.common.utils.WebClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import retrofit2.Response;
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
@ -75,13 +70,15 @@ public class BiliCookieManager {
return htmlContent;
}
public static boolean resetCookie(LoginCookieDatabaseBean cookie) {
public static boolean refreshCookie(LoginCookieDatabaseBean cookie) {
try {
LoginApi api = BiliLoginNetApiManager.getInstance().getLoginApi(cookie.getDedeUserID());
String correspondPath = getCorrespondPath(String.format("refresh_%d", System.currentTimeMillis()));
System.out.println("correspondPath = " + correspondPath);
Thread.sleep(300);
Response<FileBody<String>> body = api.getCorrespond(correspondPath).execute();
if(body.code()==404){
System.out.println("返回404");
return false;
}
System.out.println("body.code() = " + body.code());
@ -91,9 +88,13 @@ public class BiliCookieManager {
Response<HttpBody<LoginInfoBean>> newCookie = api.refreshCookie(cookie.getBiliJct(), refreshCsrf, "main_web", cookie.getRefreshToken()).execute();
LoginCookieDatabaseBean nc = BiliLoginNetApiManager.getInstance().getCookie(newCookie.headers(), newCookie.body());
nc.setGourl(cookie.getGourl());
nc.setSql_time(cookie.getSql_time());
BiliBiliLoginDatabase.getInstance().updateLoginCookie(nc);
System.out.println("返回正确");
return true;
} catch (Exception e) {
Log.e(e);
System.out.println("返回错误");
return false;
}
}

View File

@ -3,11 +3,17 @@ package com.yutou.biliapi.net;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.UserApi;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.bilibili.Controllers.BiliUserController;
import com.yutou.bilibili.services.LiveLoginService;
import com.yutou.common.inter.IHttpApiCheckCallback;
import com.yutou.common.okhttp.HttpCallback;
import com.yutou.common.okhttp.api.BaseApi;
import okhttp3.Headers;
import java.util.HashMap;
import java.util.List;
public class BiliUserNetApiManager extends BaseApi {
public static final int LOGIN_LOGOUT = 1;
@ -26,17 +32,45 @@ public class BiliUserNetApiManager extends BaseApi {
}
public UserApi getUserApi(LoginCookieDatabaseBean cookie) {
return getUserApi(cookie, null);
}
public UserApi getUserApi(LoginCookieDatabaseBean cookie, HashMap<String, String> addCookie) {
HashMap<String, String> headers = new HashMap<>();
StringBuilder ck = new StringBuilder();
if (cookie != null) {
HashMap<String, String> headers = new HashMap<>();
JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(cookie));
StringBuilder ck = new StringBuilder();
for (String key : json.keySet()) {
ck.append(key).append("=").append(json.getString(key)).append("; ");
}
}
if (addCookie != null) {
addCookie.forEach((k, v) -> ck.append(k).append("=").append(v).append("; "));
}
if(!ck.isEmpty()) {
headers.put("Cookie", ck.toString());
setHeaders(headers);
}
return createApi(UserApi.class);
}
public static void main(String[] args) {
LiveLoginService loginService = new LiveLoginService();
LoginCookieDatabaseBean cookie = loginService.getCookie("96300");
UserApi api = BiliUserNetApiManager.getInstance().getUserApi(cookie);
api.getFollowings(cookie.getDedeUserID(), "", 50, 1).enqueue(new HttpCallback<UserFollowingsBean>() {
@Override
public void onResponse(Headers headers, int code, String status, UserFollowingsBean response, String rawResponse) {
System.out.println("关注数:" + response.getTotal());
for (UserFollowingsBean.Follow follow : response.getList()) {
System.out.println(follow.getUname());
}
}
@Override
public void onFailure(Throwable throwable) {
}
});
}
}

View File

@ -0,0 +1,89 @@
package com.yutou.biliapi.net;
import com.yutou.biliapi.bean.live.SpiBean;
import com.yutou.biliapi.bean.user.UserHomeInfoBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.common.utils.Log;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class WebSignManager {
private static final int[] mixinKeyEncTab = new int[]{
46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,
36, 20, 34, 44, 52
};
private static final char[] hexDigits = "0123456789abcdef".toCharArray();
public static String md5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
char[] result = new char[messageDigest.length * 2];
for (int i = 0; i < messageDigest.length; i++) {
result[i * 2] = hexDigits[(messageDigest[i] >> 4) & 0xF];
result[i * 2 + 1] = hexDigits[messageDigest[i] & 0xF];
}
return new String(result);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String getMixinKey(String imgKey, String subKey) {
String s = imgKey + subKey;
StringBuilder key = new StringBuilder();
for (int i = 0; i < 32; i++)
key.append(s.charAt(mixinKeyEncTab[i]));
return key.toString();
}
public static String encodeURIComponent(Object o) {
return URLEncoder.encode(o.toString(), StandardCharsets.UTF_8).replace("+", "%20");
}
private static String getKey(String url) {
// 使用正则表达式匹配所需的字段
String pattern = "/(\\w+)\\.png$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(url);
if (m.find()) {
return m.group(1);
}
return null;
}
public static TreeMap<String, Object> getWebSign(TreeMap<String,Object> map, UserInfoBean userInfo) {
try {
String imgKey = getKey(userInfo.getWbiImg().getImgUrl());
String subKey = getKey(userInfo.getWbiImg().getSubUrl());
String mixinKey = getMixinKey(imgKey, subKey);
// 用TreeMap自动排序
map.put("wts", System.currentTimeMillis() / 1000);
String param = map.entrySet().stream()
.map(it -> String.format("%s=%s", it.getKey(), encodeURIComponent(it.getValue())))
.collect(Collectors.joining("&"));
String s = param + mixinKey;
String wbiSign = md5(s);
map.put("w_rid", wbiSign);
return map;
} catch (Exception e) {
Log.e(e);
}
return null;
}
}

View File

@ -4,34 +4,22 @@ import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.LoginApi;
import com.yutou.biliapi.bean.login.CheckCookieBean;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.login.UserInfoBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliCookieManager;
import com.yutou.biliapi.net.BiliLoginNetApiManager;
import com.yutou.biliapi.net.BiliUserNetApiManager;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.bilibili.datas.ReturnCode;
import com.yutou.bilibili.services.LiveLoginService;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.okhttp.HttpCallback;
import com.yutou.common.okhttp.HttpLoggingInterceptor;
import com.yutou.common.utils.Log;
import com.yutou.common.utils.RedisTools;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import okhttp3.Headers;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@ -82,7 +70,7 @@ public class BiliUserController {
} else {
returnCode = ReturnCode.RC300;
}
JSONObject login = login(loginToken.toString());
JSONObject login = loginService.login(loginToken.toString());
if (login != null && login.containsKey("qrcode")) {
return ResultData.success(login, -1, returnCode);
} else if (login != null) {
@ -92,71 +80,41 @@ public class BiliUserController {
return ResultData.success(loginToken.toString(), -1, returnCode);
}
private JSONObject login(String loginToken) {
String ret = RedisTools.get(loginToken);
if (StringUtils.hasText(ret)) {
JSONObject json = JSONObject.parseObject(ret);
if (json.getIntValue("code") == BiliLoginNetApiManager.LOGIN_SUCCESS) {
RedisTools.remove(loginToken);
}
return json;
@ResponseBody
@RequestMapping("/user/refreshCookie")
public JSONObject refreshCookie(String uid) {
if(!StringUtils.hasText(uid)){
return ResultData.fail(ReturnCode.RC999);
}
if(loginService.refreshUserCookie(uid)){
return ResultData.success(ReturnCode.RC100);
}else{
return ResultData.fail(ReturnCode.RC999);
}
BiliLoginNetApiManager.getInstance().login(new HttpCallback<LoginCookieDatabaseBean>() {
@Override
public void onResponse(Headers headers, int code, String status, LoginCookieDatabaseBean response, String rawResponse) {
JSONObject json = new JSONObject();
json.put("code", code);
if (code == BiliLoginNetApiManager.LOGIN_QRCODE) {
json.put("qrcode", rawResponse);
} else if (code == BiliLoginNetApiManager.LOGIN_SUCCESS) {
Response<HttpBody<UserInfoBean>> execute = null;
try {
execute = BiliUserNetApiManager.getInstance().getUserApi(response).getUserInfo().execute();
if (execute.isSuccessful()) {
if (execute.body() != null) {
UserInfoBean data = execute.body().getData();
LoginUserDatabaseBean userBean = new LoginUserDatabaseBean(data);
BiliBiliLoginDatabase.getInstance().initData(response, userBean).close();
json.put("user", data);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
RedisTools.set(loginToken, json.toString(), 60);
}
@Override
public void onFailure(Throwable throwable) {
}
});
return null;
}
public static void main(String[] args) {
// LiveLoginService loginService = new LiveLoginService();
/* List<LoginUserDatabaseBean> allUser = loginService.getAllUser();
LiveLoginService loginService = new LiveLoginService();
List<LoginUserDatabaseBean> allUser = loginService.getAllUser();
for (LoginUserDatabaseBean user : allUser) {
System.out.println(user.getUserInfo().getMid());
LoginApi api = BiliLoginNetApiManager.getInstance().getLoginApi(user.getUserInfo().getMid());
try {
CheckCookieBean cookie = api.checkCookie().execute().body().getData();
System.out.println("cookie = " + cookie);
if(cookie.isRefresh()){
BiliCookieManager.resetCookie(loginService.getCookie(user.getUserInfo().getMid()));
if (cookie.isRefresh()) {
boolean flag = BiliCookieManager.refreshCookie(loginService.getCookie(user.getUserInfo().getMid()));
System.out.println("flag = " + flag);
}
} catch (IOException e) {
Log.e(e);
}finally {
return;
} finally {
;
}
}*/
}
// HttpLoggingInterceptor.setLog(true);
// BiliCookieManager.resetCookie(loginService.getCookie("3493115839121644"));
RedisTools.set("test", "test", 10000);
System.out.println(RedisTools.get("test"));
}
}

View File

@ -3,12 +3,16 @@ package com.yutou.bilibili.Controllers;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.bilibili.Tools.Tools;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.bilibili.datas.ReturnCode;
import com.yutou.bilibili.services.LiveConfigService;
import com.yutou.bilibili.services.LiveLoginService;
import com.yutou.bilibili.services.LiveUserService;
import jakarta.annotation.Resource;
import lombok.val;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
@ -17,8 +21,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
@ -26,19 +30,99 @@ import java.util.List;
public class LiveConfigController {
@Resource
LiveConfigService configService;
@Resource
LiveUserService userService;
@Resource
LiveLoginService loginService;
@ResponseBody
@RequestMapping("follow")
public JSONObject getFollow(String userId, int page, int limit) {
UserFollowingsBean bean = userService.getUserFollowings(userId, page, limit);
if (bean == null) {
return ResultData.fail(ReturnCode.RC999);
}
return ResultData.success(bean, bean.getTotal());
}
@ResponseBody
@RequestMapping("follow/add")
public JSONObject addFollow(String uid, String anchorId) {
int flag = userService.followAnchor(uid, anchorId);
if (flag == 1) {
return ResultData.success(ReturnCode.RC100);
} else {
return switch (flag) {
case 0 -> ResultData.fail(-flag, "关注失败");
case -1 -> ResultData.fail(-flag, "关注失败,程序异常");
case -2 -> ResultData.fail(-flag, "关注失败UP未开通直播间");
case -3 -> ResultData.fail(-flag, "账号可能被风控,请从配置页手动配置");
case 2 -> ResultData.fail(-flag, "已在关注列表");
default -> ResultData.fail(ReturnCode.RC999);
};
}
}
@ResponseBody
@RequestMapping("follow/addList")
public JSONObject addFollowList(String uid, String array) {
if (!StringUtils.hasText(array)) {
return ResultData.fail(ReturnCode.RC500);
}
JSONArray jsonArray = JSONArray.parseArray(array);
List<UserFollowingsBean.Follow> list = jsonArray.stream()
.map(o -> {
JSONObject jsonObject = (JSONObject) o;
UserFollowingsBean.Follow follow = new UserFollowingsBean.Follow();
follow.setMid(jsonObject.getString("mid"));
follow.setUname(jsonObject.getString("uname"));
return follow;
}).toList();
return ResultData.success(userService.followAll(uid,list));
}
@ResponseBody
@RequestMapping("follow/check")
public JSONObject checkFollow(String userId) {
List<ResultData<String>> list = new ArrayList<>();
if (StringUtils.hasText(userId)) {
list.add(getFollowStatus(userId, userService.checkFollow(userId)));
} else {
for (LoginUserDatabaseBean user : loginService.getAllUser()) {
list.add(getFollowStatus(user.getUserInfo().getMid(), userService.checkFollow(user.getUserInfo().getMid())));
}
}
return ResultData.success(list);
}
@ResponseBody
@RequestMapping("follow/all")
public JSONObject getAllFollow(String userId) {
return ResultData.success(userService.followAll(userId));
}
@ResponseBody
@RequestMapping("follow/confirm")
public JSONObject confirmAllFollow(String userId) {
userService.confirmFollow(userId);
return ResultData.success(ReturnCode.RC100);
}
@RequestMapping(value = "set", method = RequestMethod.POST)
@ResponseBody
public JSONObject setConfig(String url, LiveConfigDatabaseBean bean) {
if(!bean.verifyLiveTimer()){
return ResultData.fail(ReturnCode.RC999.getCode(),"视频录制时间格式错误");
if (!bean.verifyLiveTimer()) {
return ResultData.fail(ReturnCode.RC999.getCode(), "视频录制时间格式错误");
}
if(!bean.verifyDanmuTimer()){
return ResultData.fail(ReturnCode.RC999.getCode(),"弹幕录制时间格式错误");
if (!bean.verifyDanmuTimer()) {
return ResultData.fail(ReturnCode.RC999.getCode(), "弹幕录制时间格式错误");
}
if(!url.startsWith("https://live.bilibili.com/")){
if(!configService.checkUrl(url)){
return ResultData.fail(ReturnCode.RC999.getCode(),"房间地址/房间号错误");
if (!url.startsWith("https://live.bilibili.com/")) {
if (!configService.checkUrl(url)) {
return ResultData.fail(ReturnCode.RC999.getCode(), "房间地址/房间号错误");
}
}
LiveConfigDatabaseBean config = configService.addConfig(url, bean);
@ -51,11 +135,11 @@ public class LiveConfigController {
@RequestMapping(value = "update", method = RequestMethod.POST)
@ResponseBody
public JSONObject updateConfig(String roomId, LiveConfigDatabaseBean bean) {
if(!bean.verifyLiveTimer()){
return ResultData.fail(ReturnCode.RC999.getCode(),"视频录制时间格式错误");
if (!bean.verifyLiveTimer()) {
return ResultData.fail(ReturnCode.RC999.getCode(), "视频录制时间格式错误");
}
if(!bean.verifyDanmuTimer()){
return ResultData.fail(ReturnCode.RC999.getCode(),"弹幕录制时间格式错误");
if (!bean.verifyDanmuTimer()) {
return ResultData.fail(ReturnCode.RC999.getCode(), "弹幕录制时间格式错误");
}
LiveConfigDatabaseBean config = configService.updateConfig(new String(roomId), bean);
@ -80,15 +164,15 @@ public class LiveConfigController {
@RequestMapping(value = "all", method = RequestMethod.GET)
@ResponseBody
public JSONObject getAllConfig(int page,int limit) {
List<LiveConfigDatabaseBean> config ;
if(page==-1||limit==-1) {
config=configService.getAllConfig();
}else{
config=configService.getConfigs(page, limit);
public JSONObject getAllConfig(int page, int limit) {
List<LiveConfigDatabaseBean> config;
if (page == -1 || limit == -1) {
config = configService.getAllConfig();
} else {
config = configService.getConfigs(page, limit);
}
if (config != null) {
return ResultData.success(config,configService.getConfigCount());
return ResultData.success(config, configService.getConfigCount());
}
return ResultData.fail(ReturnCode.RC999);
}
@ -96,7 +180,7 @@ public class LiveConfigController {
@RequestMapping(value = "delete", method = RequestMethod.GET)
@ResponseBody
public JSONObject deleteConfig(String roomId) {
if ("0".equals(roomId)|| !StringUtils.hasText(roomId)) {
if ("0".equals(roomId) || !StringUtils.hasText(roomId)) {
return ResultData.fail(ReturnCode.RC999);
}
boolean flag = configService.deleteConfig(roomId);
@ -110,4 +194,27 @@ public class LiveConfigController {
public ResponseEntity<FileSystemResource> getFace(String roomId) {
return Tools.getFile(configService.getFace(roomId));
}
private ResultData<String> getFollowStatus(String userId, ResultData<UserFollowingsBean.Follow> follow) {
ResultData<String> resultData = new ResultData<>();
resultData.setData(userId);
if (follow == null) {
resultData.setMessage(userId + ":没有相关任务");
resultData.setStatus(-1);
return resultData;
}
resultData.setCount(follow.getCount());
if (follow.getStatus() == -100) {
resultData.setMessage(userId + ":处理完成");
resultData.setStatus(-100);
} else {
if (follow.getData() == null) {
resultData.setMessage(userId + ":正在等待");
} else {
resultData.setMessage(userId + ":正在处理:" + follow.getData().getUname() + "(" + follow.getStatus() + "/" + follow.getCount() + ")");
}
resultData.setStatus(follow.getStatus());
}
return resultData;
}
}

View File

@ -25,4 +25,10 @@ public class LiveController {
public JSONObject getLiveList(int page,int limit) {
return ResultData.success(liveService.getLiveList(page,limit), liveService.getConfigCount());
}
@RequestMapping("/live/gift/info")
@ResponseBody
public JSONObject download(String roomId, String videoId) {
return ResultData.success(liveService.getGiftInfo(roomId,videoId));
}
}

View File

@ -94,10 +94,9 @@ public class VideoFileController {
// 返回带有 MIME 类型的数据 URI
return base64Image;
} catch (Exception e) {
e.printStackTrace();
} catch (Exception ignored) {
return "/assets/def.png";
}
return "";
}
@RequestMapping("/video/play")

View File

@ -3,52 +3,85 @@ package com.yutou.bilibili.Tools;
import com.yutou.common.utils.Log;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DateFormatUtils {
public static String format(Date date, String format) {
return new SimpleDateFormat(format).format(date);
private final Map<String, ThreadLocal<SimpleDateFormat>> formats = new ConcurrentHashMap<>();
private static volatile DateFormatUtils utils;
public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
private DateFormatUtils() {}
public static DateFormatUtils getInstance() {
if (utils == null) {
synchronized (DateFormatUtils.class) {
if (utils == null) {
utils = new DateFormatUtils();
}
}
}
return utils;
}
public static String format(long time, String format) {
return new SimpleDateFormat(format).format(new Date(time));
public String format(Date date, String format) {
getFormat(format).applyPattern(format);
return getFormat(format).format(date);
}
public static String format(long time) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(time));
public String format(long time, String format) {
return getFormat(format).format(new Date(time));
}
public static String format(Date date) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date);
public String format(long time) {
if (time < 1000000000) {
time *= 1000;
}
return getFormat().format(new Date(time));
}
public static String format() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
public String format(Date date) {
return getFormat().format(date);
}
public static Date parseTimer(String date) {
public String format() {
return getFormat().format(new Date());
}
public Date parseTimer(String date) {
return parse(date, "HH:mm:ss");
}
public static Date parse(String date, String format) {
public Date parse(String date, String format) {
try {
return new SimpleDateFormat(format).parse(date);
} catch (Exception e) {
Log.e(e);
return getFormat(format).parse(date);
} catch (ParseException e) {
System.err.println("Error parsing date: " + e.getMessage());
return null;
}
}
public static String parseString(String date,String format){
Date time = parse(date, format);
return format(time,format);
}
public static boolean checkTime(List<String> weeks, String recordDate) {
public String parseString(String date, String format) {
Date time = parse(date, format);
return format(time, format);
}
public String formatMillis(long millis) {
Duration duration = Duration.ofMillis(millis);
int seconds = (int) (duration.getSeconds() % 60);
int minutes = (int) ((duration.getSeconds() / 60) % 60);
int hours = (int) (duration.getSeconds() / 3600);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public boolean checkTime(List<String> weeks, String recordDate) {
if (!StringUtils.hasText(recordDate)) {
recordDate = "00:00:00 - 23:59:59";
}
@ -78,6 +111,11 @@ public class DateFormatUtils {
(currentTime.isBefore(endTime) || currentTime.equals(endTime));
return isWithinRange && isSpecifiedWeekDay;
}
private SimpleDateFormat getFormat() {
return getFormat(DEFAULT_PATTERN);
}
private SimpleDateFormat getFormat(String format) {
return formats.computeIfAbsent(format, key -> ThreadLocal.withInitial(() -> new SimpleDateFormat(key))).get();
}
}

View File

@ -13,6 +13,7 @@ public class LiveData extends BaseBean {
private String anchorFace;
private String title;
private String cover;
private String liveTime;
private boolean isLive;
private boolean isDanmu;
private boolean isDownloadVideo;

View File

@ -62,8 +62,8 @@ public class LiveDanmuService {
long videoTime = FFmpegUtils.getVideoTime(videoFile) + videoDatabaseBean.getStartTime().getTime();
Log.i("开始时间:" + videoDatabaseBean.getStartTime().getTime());
Log.i("结束时间:" + videoTime);
String startTime = DateFormatUtils.format(videoDatabaseBean.getStartTime());
String endTime = DateFormatUtils.format(videoTime);
String startTime = DateFormatUtils.getInstance().format(videoDatabaseBean.getStartTime());
String endTime = DateFormatUtils.getInstance().format(videoTime);
List<LiveDanmuDatabaseBean> danmus = database.getOfTime(startTime, endTime, LiveDanmuDatabaseBean.class);
Log.i("弹幕数量:" + danmus.size());
AssTools assTools = new AssTools(videoFile.getName().replace(".flv", ""), videoDatabaseBean.getStartTime());
@ -86,14 +86,7 @@ public class LiveDanmuService {
public LiveVideoDanmu getDanmu(String roomId, String videoId) {
LiveVideoDanmu danmus = new LiveVideoDanmu();
BiliLiveDatabase liveDatabase = new BiliLiveDatabase(LiveRoomConfig.buildConfig(roomId));
LiveVideoDatabaseBean videoBean = null;
for (LiveVideoDatabaseBean info : liveDatabase.getLiveInfos()) {
System.out.println(videoId + " " + info.getSql_time().getTime());
if (videoId.trim().equals(String.valueOf(info.getSql_time().getTime()))) {
videoBean = info;
break;
}
}
LiveVideoDatabaseBean videoBean = liveDatabase.getVideo(videoId);
if (videoBean == null) {
return new LiveVideoDanmu();
}
@ -104,8 +97,8 @@ public class LiveDanmuService {
long videoTime = FFmpegUtils.getVideoTime(videoFile);
long startTime = Long.parseLong(videoId);
long endTime = Long.parseLong(videoId) + videoTime;
List<LiveDanmuDatabaseBean> danmuList = liveDatabase.getOfTime(DateFormatUtils.format(startTime), DateFormatUtils.format(endTime), LiveDanmuDatabaseBean.class);
List<LiveSuperChatDatabaseBean> superChatList = liveDatabase.getOfTime(DateFormatUtils.format(startTime), DateFormatUtils.format(endTime), LiveSuperChatDatabaseBean.class);
List<LiveDanmuDatabaseBean> danmuList = liveDatabase.getOfTime(DateFormatUtils.getInstance().format(startTime), DateFormatUtils.getInstance().format(endTime), LiveDanmuDatabaseBean.class);
List<LiveSuperChatDatabaseBean> superChatList = liveDatabase.getOfTime(DateFormatUtils.getInstance().format(startTime), DateFormatUtils.getInstance().format(endTime), LiveSuperChatDatabaseBean.class);
for (LiveDanmuDatabaseBean bean : danmuList) {
LiveVideoDanmu.Danmu danmu = createDanmu(bean, startTime);
danmus.getDanmu().add(danmu);

View File

@ -1,17 +1,24 @@
package com.yutou.bilibili.services;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.LoginApi;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginInfoBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.login.QRCodeGenerateBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliCookieManager;
import com.yutou.biliapi.net.BiliLoginNetApiManager;
import com.yutou.biliapi.net.BiliUserNetApiManager;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.okhttp.HttpCallback;
import com.yutou.common.utils.RedisTools;
import okhttp3.Headers;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import retrofit2.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
@ -57,10 +64,59 @@ public class LiveLoginService {
return loginDatabase.getAllUser();
}
public List<LoginCookieDatabaseBean> getAllUserCookie(){
public List<LoginCookieDatabaseBean> getAllUserCookie() {
return loginDatabase.getAllCookies();
}
public LoginCookieDatabaseBean getCookie(String userId) {
return loginDatabase.getCookie(userId);
}
public JSONObject login(String loginToken) {
String ret = RedisTools.get(loginToken);
if (StringUtils.hasText(ret)) {
JSONObject json = JSONObject.parseObject(ret);
if (json.getIntValue("code") == BiliLoginNetApiManager.LOGIN_SUCCESS) {
RedisTools.remove(loginToken);
}
return json;
}
BiliLoginNetApiManager.getInstance().login(new HttpCallback<LoginCookieDatabaseBean>() {
@Override
public void onResponse(Headers headers, int code, String status, LoginCookieDatabaseBean response, String rawResponse) {
JSONObject json = new JSONObject();
json.put("code", code);
if (code == BiliLoginNetApiManager.LOGIN_QRCODE) {
json.put("qrcode", rawResponse);
} else if (code == BiliLoginNetApiManager.LOGIN_SUCCESS) {
Response<HttpBody<UserInfoBean>> execute = null;
try {
execute = BiliUserNetApiManager.getInstance().getUserApi(response).getUserInfo().execute();
if (execute.isSuccessful()) {
if (execute.body() != null) {
UserInfoBean data = execute.body().getData();
LoginUserDatabaseBean userBean = new LoginUserDatabaseBean(data);
BiliBiliLoginDatabase.getInstance().initData(response, userBean).close();
json.put("user", data);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
RedisTools.set(loginToken, json.toString(), 60);
}
@Override
public void onFailure(Throwable throwable) {
}
});
return null;
}
public boolean refreshUserCookie(String uid) {
return BiliCookieManager.refreshCookie(loginDatabase.getCookie(uid));
}
}

View File

@ -4,24 +4,27 @@ import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.LiveApi;
import com.yutou.biliapi.bean.live.LiveAnchorInfo;
import com.yutou.biliapi.bean.live.LiveRoomConfig;
import com.yutou.biliapi.bean.live.LiveRoomInfo;
import com.yutou.biliapi.bean.live.LiveRoomPlayInfo;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.live.database.LiveVideoDatabaseBean;
import com.yutou.biliapi.databases.BiliLiveConfigDatabase;
import com.yutou.biliapi.databases.BiliLiveDatabase;
import com.yutou.biliapi.net.BiliLiveNetApiManager;
import com.yutou.bilibili.Tools.DateFormatUtils;
import com.yutou.bilibili.datas.web.LiveData;
import com.yutou.common.okhttp.BaseBean;
import com.yutou.common.okhttp.HttpLoggingInterceptor;
import com.yutou.common.utils.FFmpegUtils;
import com.yutou.common.utils.Log;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.*;
@Service
public class LiveService {
@ -36,26 +39,34 @@ public class LiveService {
liveConfigDatabase = new BiliLiveConfigDatabase();
api = BiliLiveNetApiManager.getInstance().getApi(null);
}
public int getConfigCount(){
public int getConfigCount() {
return liveConfigDatabase.getAllConfig().size();
}
public List<LiveData> getLiveList(int page,int limit) {
public List<LiveData> getLiveList(int page, int limit) {
List<LiveConfigDatabaseBean> allConfig = liveConfigDatabase.getAllConfig();
List<LiveData> liveDataList = new ArrayList<>();
JSONArray uids=new JSONArray();
JSONObject param=new JSONObject();
if (allConfig.isEmpty()) {
return liveDataList;
}
JSONArray uids = new JSONArray();
JSONObject param = new JSONObject();
for (LiveConfigDatabaseBean bean : allConfig) {
uids.add(bean.getAnchorUid());
}
param.put("uids",uids);
param.put("uids", uids);
try {
Map<String, LiveAnchorInfo> map = api.getLiveRoomStatus(param).execute().body().getData();
if (map == null) {
map = new HashMap<>();
}
List<LiveAnchorInfo> onlineList = new ArrayList<>();
List<LiveAnchorInfo> offlineList = new ArrayList<>();
for (LiveAnchorInfo info : map.values()) {
if(info.getLiveStatus()==1){
if (info.getLiveStatus() == 1) {
onlineList.add(info);
}else{
} else {
offlineList.add(info);
}
}
@ -73,6 +84,11 @@ public class LiveService {
liveData.setAnchorUid(info.getUid());
liveData.setAnchorName(info.getUname());
liveData.setAnchorFace(info.getFace());
if (info.getLiveTime() == 0) {
liveData.setLiveTime("未开播");
} else {
liveData.setLiveTime(DateFormatUtils.getInstance().formatMillis(System.currentTimeMillis() - info.getLiveTime()*1000));
}
liveData.setDownloadVideo(videoDownloadService.checkDownload(info.getRoomId()));
liveData.setDanmu(danmuService.check(info.getRoomId()));
liveData.setTitle(info.getTitle());
@ -91,9 +107,25 @@ public class LiveService {
return liveDataList;
}
public JSONObject getGiftInfo(String roomId, String videoId) {
BiliLiveDatabase database = new BiliLiveDatabase(LiveRoomConfig.buildConfig(roomId));
LiveVideoDatabaseBean videoBean = database.getVideo(videoId);
if (videoBean == null) {
return null;
}
File videoFile = new File(videoBean.getPath().replace(".flv", ".mp4"));
if (!videoFile.exists()) {
videoFile = new File(videoBean.getPath());
}
long videoTime = FFmpegUtils.getVideoTime(videoFile);
long startTime = Long.parseLong(videoId);
long endTime = Long.parseLong(videoId) + videoTime;
return database.getGiftInfo(startTime, endTime);
}
public static void main(String[] args) {
HttpLoggingInterceptor.setLog(true);
LiveService service=new LiveService();
LiveService service = new LiveService();
List<LiveData> data = service.getLiveList(1, 16);
System.out.println(data.size());
}

View File

@ -0,0 +1,192 @@
package com.yutou.bilibili.services;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.UserApi;
import com.yutou.biliapi.bean.live.SpiBean;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.biliapi.bean.user.UserHomeInfoBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliCookieManager;
import com.yutou.biliapi.net.BiliUserNetApiManager;
import com.yutou.biliapi.net.WebSignManager;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.utils.Log;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Service;
import retrofit2.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Service
public class LiveUserService {
@Resource
LiveLoginService userLoginService;
@Resource
LiveConfigService configService;
public UserFollowingsBean getUserFollowings(String userId, int page, int num) {
LoginCookieDatabaseBean cookie = userLoginService.getCookie(userId);
UserApi api = BiliUserNetApiManager.getInstance().getUserApi(cookie);
try {
HttpBody<UserFollowingsBean> body = api.getFollowings(cookie.getDedeUserID(), "", num, page).execute().body();
return body.getData();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public UserHomeInfoBean getUserHome(LoginCookieDatabaseBean cookie, String mid, UserInfoBean userInfo, SpiBean spiBean) {
try {
TreeMap<String, Object> map = new TreeMap<>();
map.put("mid", mid);
// map.put("web_location", "1550101");
// map.put("dm_img_inter", JSONObject.parseObject("{\"ds\":[],\"wh\":[5746,6797,28],\"of\":[276,552,276]}"));
map.put("dm_img_list", "[]");
map.put("dm_img_str", "V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ");
map.put("dm_cover_img_str", "QU5HTEUgKEFNRCwgQU1EIFJhZGVvbiA3ODBNIEdyYXBoaWNzICgweDAwMDAxNUJGKSBEaXJlY3QzRDExIHZzXzVfMCBwc181XzAsIEQzRDExKUdvb2dsZSBJbmMuIChBTU");
map = WebSignManager.getWebSign(map, userInfo);
HashMap<String, String> tmap = new HashMap<>();
tmap.put("buvid3", spiBean.getB_3());
tmap.put("buvid4", spiBean.getB_4());
Response<HttpBody<UserHomeInfoBean>> execute = BiliUserNetApiManager.getInstance().getUserApi(cookie, tmap).getWbiAccInfo(map).execute();
if (execute.body().getCode() == -352) {
return null;
}
return execute.body().getData();
} catch (Exception e) {
Log.e(e);
}
return null;
}
public int followAnchor(String uid, String anchorUid) {
try {
LoginCookieDatabaseBean cookie = BiliBiliLoginDatabase.getInstance().getCookie(uid);
UserApi api = BiliUserNetApiManager.getInstance().getUserApi(cookie);
UserInfoBean userInfo = api.getUserInfo().execute().body().getData();
SpiBean spiBean = api.getFingerSpi().execute().body().getData();
UserHomeInfoBean userHome = getUserHome(cookie, anchorUid, userInfo, spiBean);
if (userHome == null) {
return -3;//账号被风控
}
if (userHome.getLiveRoom() == null || userHome.getLiveRoom().getRoomid() == 0) {
return -2;//未开通直播间
}
LiveConfigDatabaseBean bean = configService.getConfig(String.valueOf(userHome.getLiveRoom().getRoomid()));
if (bean != null) {
return 2;//已关注
}
LiveConfigDatabaseBean config = configService.addConfig(userHome.getLiveRoom().getUrl(), new LiveConfigDatabaseBean());
if (config != null) {
return 1;
}
} catch (Exception e) {
Log.e(e);
return -1;//其他异常
}
return 0;//添加失败
}
public void confirmFollow(String uid) {
if (followTaskMap.containsKey(uid)) {
followTaskMap.get(uid).setStop(true);
}
followTaskMap.remove(uid);
}
public ResultData<UserFollowingsBean.Follow> checkFollow(String uid) {
if (followTaskMap.containsKey(uid)) {
return followTaskMap.get(uid).getFollowCount();
}
return null;
}
private final Map<String, FollowTask> followTaskMap = new HashMap<>();
public ResultData<UserFollowingsBean.Follow> followAll(String userId, List<UserFollowingsBean.Follow> follows) {
if (followTaskMap.containsKey(userId)) {
return followTaskMap.get(userId).getFollowCount();
}
FollowTask task = new FollowTask();
task.setUid(userId);
task.setFollowList(follows);
followTaskMap.put(userId, task);
task.start();
return task.getFollowCount();
}
public ResultData<UserFollowingsBean.Follow> followAll(String userId) {
return followAll(userId, null);
}
private class FollowTask extends Thread {
@Setter
private String uid;
@Setter
private List<UserFollowingsBean.Follow> followList = null;
@Getter
private ResultData<UserFollowingsBean.Follow> followCount = new ResultData<>();
@Setter
private boolean isStop = false;
@Override
public void run() {
int page = 1;
UserFollowingsBean bean = null;
if (followList == null) {
bean = getUserFollowings(uid, page, 50);
} else {
bean = new UserFollowingsBean();
bean.setTotal(followList.size());
bean.setList(followList);
}
int count = bean.getList().size();
while (count != bean.getTotal() && !isStop && followList == null) {
UserFollowingsBean tmp = getUserFollowings(uid, ++page, 50);
count += tmp.getList().size();
bean.getList().addAll(tmp.getList());
}
followCount.setCount(bean.getTotal());
followCount.setStatus(1);
count = 0;
for (UserFollowingsBean.Follow follow : bean.getList()) {
if (isStop) {
break;
}
if (followAnchor(uid, follow.getMid()) == 1) {
followCount.setData(follow);
followCount.setMessage(follow.getUname());
followCount.setStatus(++count);
}
}
followCount.setStatus(-100);
}
}
public static void main(String[] args) throws InterruptedException {
LiveUserService service = new LiveUserService();
service.userLoginService = new LiveLoginService();
service.configService = new LiveConfigService();
while (service.followAll("96300").getStatus() != 100) {
System.out.println("关注:" + service.checkFollow("96300"));
if (service.checkFollow("96300").getStatus() == 10) {
service.confirmFollow("96300");
break;
}
}
System.out.println(service.checkFollow("96300"));
}
}

View File

@ -1,21 +0,0 @@
package com.yutou.bilibili.services;
import com.yutou.biliapi.bean.live.LiveRoomConfig;
import com.yutou.biliapi.bean.live.database.LiveDanmuDatabaseBean;
import com.yutou.biliapi.bean.live.database.LiveVideoDatabaseBean;
import com.yutou.biliapi.databases.BiliLiveDatabase;
import com.yutou.bilibili.datas.web.LiveVideoDanmu;
import com.yutou.common.utils.FFmpegUtils;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Service
public class LiveVideoDanmuService {
}

View File

@ -342,7 +342,7 @@ public class LiveVideoDownloadService {
private Map<String, List<VideoFilePath>> getVideoInfo(List<LiveVideoDatabaseBean> videoList) {
Map<String, List<VideoFilePath>> map = new HashMap<>();
for (LiveVideoDatabaseBean bean : videoList) {
String date = DateFormatUtils.format(bean.getSql_time(), "yyyy-MM-dd");
String date = DateFormatUtils.getInstance().format(bean.getSql_time(), "yyyy-MM-dd");
if (!map.containsKey(date)) {
map.put(date, new ArrayList<>());
}

View File

@ -1,8 +0,0 @@
package com.yutou.bilibili.services;
import org.springframework.stereotype.Service;
@Service
public class LiveVideoService {
}

View File

@ -48,7 +48,7 @@ public class SystemService {
scheduled = timer.scheduleAtFixedRate(() -> {
List<LiveConfigDatabaseBean> list = liveConfigDatabase.getAllConfig();
Log.i("循环任务:" + list.size());
if (DateFormatUtils.checkTime(null, resetTimer)) {
if (DateFormatUtils.getInstance().checkTime(null, resetTimer)) {
videoService.clearUserStopList();
danmuService.clearUserList();
}

View File

@ -145,6 +145,8 @@ public abstract class SQLiteManager {
statement.setObject(i++, json.get(key));
} else if (json.get(key) instanceof Boolean) {
statement.setBoolean(i++, json.getBoolean(key));
} else if(json.get(key) instanceof Date){
statement.setLong(i++, json.getDate(key).getTime());
} else {
statement.setObject(i++, json.get(key));
}
@ -152,47 +154,66 @@ public abstract class SQLiteManager {
statement.execute();
statement.close();
} catch (SQLException e) {
Log.e(e,sb);
Log.e(e, sb);
throw new RuntimeException(e);
}
}
protected <T extends AbsDatabasesBean> void update(T t) {
try {
String id = DateUtils.format(t.getSql_time(), "yyyy-MM-dd HH:mm:ss.SSS");
if (id.endsWith("0")) {
id = id.substring(0, id.length() - 1);
} else if (id.endsWith("00")) {
id = id.substring(0, id.length() - 2);
} else if (id.endsWith("000")) {
id = id.substring(0, id.length() - 4);
}
Statement statement = getConnection().createStatement();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE `").append(t.getTableName()).append("` ");
sb.append("SET ");
StringBuilder setPart = new StringBuilder();
JSONObject json = t.toJson();
Set<String> keySet = json.keySet();
for (String key : keySet) {
if ("id".equals(key) || "sql_time".equals(key)) {
continue;
}
sb.append(" `").append(key).append("` = ");
setPart.append("`").append(key).append("` = ?, ");
}
setPart.deleteCharAt(setPart.length() - 2);
sb.append("UPDATE `").append(t.getTableName()).append("` ");
sb.append("SET ").append(setPart);
sb.append(" WHERE `sql_time` = ?");
PreparedStatement statement = getConnection().prepareStatement(sb.toString());
int i = 1;
for (String key : keySet) {
if ("id".equals(key) || "sql_time".equals(key)) {
continue;
}
if (json.get(key) instanceof String) {
sb.append("'").append(json.get(key)).append("', ");
statement.setString(i++, json.getString(key));
} else if (json.get(key) instanceof Integer) {
statement.setInt(i++, json.getInteger(key));
} else if (json.get(key) instanceof Long) {
statement.setLong(i++, json.getLong(key));
} else if (json.get(key) instanceof Boolean) {
statement.setBoolean(i++, json.getBoolean(key));
} else if(json.get(key) instanceof Date){
statement.setLong(i++, json.getDate(key).getTime());
} else {
sb.append(json.get(key)).append(", ");
statement.setObject(i++, json.get(key));
}
}
sb.deleteCharAt(sb.length() - 2);
sb.append(" WHERE `sql_time` = ").append("'").append(id).append("'");
statement.executeUpdate(sb.toString());
// 设置 sql_time 的值
String id = String.valueOf(t.getSql_time());
statement.setString(i, id);
statement.executeUpdate();
statement.close();
} catch (Exception e) {
} catch (SQLException e) {
Log.e(e);
throw new RuntimeException(e);
}
}
protected JSONArray getJSONArray(String table) {
@ -282,6 +303,22 @@ public abstract class SQLiteManager {
return list;
}
protected JSONArray get(String sql) {
JSONArray json = new JSONArray();
try {
ResultSet resultSet;
Statement statement = getConnection().createStatement();
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
json.add(getSQL(resultSet));
}
statement.closeOnCompletion();
} catch (Exception e) {
throw new RuntimeException(e);
}
return json;
}
protected <T extends AbsDatabasesBean> boolean delete(T t) {
try {
String id = DateUtils.format(t.getSql_time(), "yyyy-MM-dd HH:mm:ss.SSS");

View File

@ -38,6 +38,7 @@ public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T>
return (T) body;
} catch (Exception e) {
Log.e(e);
Log.e(string);
body = new HttpBody();
body.setSrc(string);
}