This commit is contained in:
zlzw 2024-10-30 18:27:37 +08:00
parent 4d4d409cc7
commit 4b04c1863b
15 changed files with 576 additions and 336 deletions

View File

@ -9,13 +9,54 @@
<body> <body>
<div id="header"></div> <div id="header"></div>
<body>
<div id="view"></div>
</body> </body>
<script id="demo" type="text/html">
<h3>{{ d.title }}</h3>
<ul>
{{# layui.each(d.list, function(index, item){ }}
<li>
<span>{{ item.modname }}</span>
<span>{{ item.alias }}</span>
<span>{{ item.site || '' }}</span>
</li>
{{# }); }}
{{# if(d.list.length === 0){ }}
无数据
{{# } }}
</ul>
</script>
<script src="/layui/layui.js"></script> <script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script> <script src="/js/jquery-3.2.1.js"></script>
<script src="/js/CommonConfig.js"></script> <script src="/js/CommonConfig.js"></script>
<script> <script>
headerModel=3; headerModel=3;
$('#header').load("/html/header.html"); $('#header').load("/html/header.html");
layui.use(['form', 'laytpl'], function () {
var form = layui.form;
var layer = layui.layer;
var laytpl = layui.laytpl
var data = { //数据
"title":"Layui常用模块"
,"list":[{"modname":"弹层","alias":"layer","site":"layer.layui99.com"},{"modname":"表单","alias":"form"}]
}
var getTpl = $("#demo").get(0).innerHTML
,view = document.getElementById('view');
laytpl(getTpl).render(data, function(html){
view.innerHTML = html;
console.log(html)
});
})
</script> </script>
<style> <style>

View File

@ -10,25 +10,12 @@
<body> <body>
<div id="header"></div> <div id="header"></div>
<img crossorigin="use-credentials" src="https://i0.hdslb.com/bfs/face/398e4b6654bbb64d87f645b9b45591e4f959f6ce.jpg" alt="Smiley face" > <table class="layui-hide" id="roomList" lay-filter="roomTable"></table>
<table class="layui-hide" id="test" lay-filter="test"></table>
</body> </body>
<script type="text/html" id="toolbarDemo"> <script type="text/html" id="toolbarDemo">
<div class="layui-btn-container"> <div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button> <button class="layui-btn layui-btn-sm" onclick="createRoom()">添加新房间</button>
<button class="layui-btn layui-btn-sm" lay-event="getData">获取当前页数据</button> <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" id="dropdownButton">
下拉按钮
<i class="layui-icon layui-icon-down layui-font-12"></i>
</button>
<button class="layui-btn layui-btn-sm layui-bg-blue" id="reloadTest">
重载测试
<i class="layui-icon layui-icon-down layui-font-12"></i>
</button>
<button class="layui-btn layui-btn-sm layui-btn-primary" id="rowMode">
<span>{{= d.lineStyle ? '多行' : '单行' }}模式</span>
<i class="layui-icon layui-icon-down layui-font-12"></i>
</button>
</div> </div>
</script> </script>
<script type="text/html" id="toolDemo"> <script type="text/html" id="toolDemo">
@ -43,19 +30,51 @@
<script src="/layui/layui.js"></script> <script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script> <script src="/js/jquery-3.2.1.js"></script>
<script src="/js/CommonConfig.js"></script> <script src="/js/CommonConfig.js"></script>
<script src="/js/httpUtils.js"></script>
<script> <script>
headerModel = 1; headerModel = 1;
$('#header').load("/html/header.html"); $('#header').load("/html/header.html");
</script> </script>
<script> <script>
layui.use(['table', 'dropdown'],function () { function showImage(url, imgElement) {
getHttpImage(url)
.then(imageUrl => {
imgElement.src = imageUrl;
})
.catch(error => {
console.error("Error loading image:", error);
// 可以在这里设置一个默认图片或者显示错误信息
imgElement.src = 'default-image.jpg';
});
}
function createRoom() {
layer.open({
type: 2,
title:"添加新房间",
area: ['500px', '400px'],
content: '/html/ui/createConfig.html'
});
// createUi("/html/ui/createConfig.html")
// .then(html => {
// layer.open({
// type: 1,
// area: ['500px', '300px'],
// content: '/html/ui/createConfig.html'
// });
// })
}
</script>
<script>
layui.use(['table', 'dropdown'], function () {
var table = layui.table; var table = layui.table;
var dropdown = layui.dropdown; var dropdown = layui.dropdown;
// 创建渲染实例 // 创建渲染实例
table.render({ table.render({
elem: '#test', elem: '#roomList',
url: '/live/config/all', url: '/live/config/all',
toolbar: '#toolbarDemo', toolbar: '#toolbarDemo',
@ -69,14 +88,14 @@
"code": res.status, //解析接口状态 "code": res.status, //解析接口状态
"msg": res.message, //解析提示文本 "msg": res.message, //解析提示文本
"data": res.data, //解析数据列表 "data": res.data, //解析数据列表
"count":res.count "count": res.count
}; };
}, },
cols: [[ cols: [[
{ type: 'checkbox', fixed: 'left' }, { type: 'checkbox', fixed: 'left' },
{ field: 'anchorUid', title: 'UID', width: 80, sort: true, fixed: 'left' }, { field: 'anchorUid', title: 'UID', width: 80, sort: true, fixed: 'left' },
{ field: 'anchorName', title: '用户名', width: 100, fixed: 'left' }, { field: 'anchorName', title: '用户名', width: 100, fixed: 'left' },
{ field: 'anchorFace', title: '头像', width: 80,templet:'<div><image src="{{= d.anchorFace }}"></div>' }, { field: 'anchorFace', title: '头像', width: 80, templet: '<div><image src="" onerror="showImage(\'{{= d.anchorFace }}\',this);" style="width: 30px;height: 30px;"></div>' },
{ field: 'live_room_id', title: '房间号', width: 80 }, { field: 'live_room_id', title: '房间号', width: 80 },
{ field: 'recordPath', title: '保存路径', width: 120 }, { field: 'recordPath', title: '保存路径', width: 120 },
{ field: 'recordDanmu', title: '录制弹幕', width: 120, sort: true }, { field: 'recordDanmu', title: '录制弹幕', width: 120, sort: true },
@ -89,276 +108,70 @@
{ fixed: "right", title: "操作", width: 190, align: "center", toolbar: "#toolDemo" } { fixed: "right", title: "操作", width: 190, align: "center", toolbar: "#toolDemo" }
]], ]],
done: function () { done: function () {
var id = this.id; done();
// 下拉按钮测试
dropdown.render({
elem: '#dropdownButton', // 可绑定在任意元素中,此处以上述按钮为例
data: [{
id: 'add',
title: '添加'
}, {
id: 'update',
title: '编辑'
}, {
id: 'delete',
title: '删除'
}],
// 菜单被点击的事件
click: function (obj) {
var checkStatus = table.checkStatus(id)
var data = checkStatus.data; // 获取选中的数据
switch (obj.id) {
case 'add':
layer.open({
title: '添加',
type: 1,
area: ['80%', '80%'],
content: '<div style="padding: 16px;">自定义表单元素</div>'
});
break;
case 'update':
if (data.length !== 1) return layer.msg('请选择一行');
layer.open({
title: '编辑',
type: 1,
area: ['80%', '80%'],
content: '<div style="padding: 16px;">自定义表单元素</div>'
});
break;
case 'delete':
if (data.length === 0) {
return layer.msg('请选择一行');
}
layer.msg('delete event');
break;
}
}
});
// 重载测试
dropdown.render({
elem: '#reloadTest', // 可绑定在任意元素中,此处以上述按钮为例
data: [{
id: 'reload',
title: '重载'
}, {
id: 'reload-deep',
title: '重载 - 参数叠加'
}, {
id: 'reloadData',
title: '仅重载数据'
}, {
id: 'reloadData-deep',
title: '仅重载数据 - 参数叠加'
}],
// 菜单被点击的事件
click: function (obj) {
switch (obj.id) {
case 'reload':
// 重载 - 默认(参数重置)
table.reload('test', {
where: {
abc: '123456',
//test: '新的 test2',
//token: '新的 token2'
},
/*
cols: [[ // 重置表头
{type: 'checkbox', fixed: 'left'},
{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true, totalRow: '合计:'},
{field:'sex', title:'性别', width:80, edit: 'text', sort: true},
{field:'experience', title:'积分', width:80, sort: true, totalRow: true, templet: '<div>{{= d.experience }} 分</div>'},
{field:'logins', title:'登入次数', width:100, sort: true, totalRow: true},
{field:'joinTime', title:'加入时间', width:120}
]]
*/
});
break;
case 'reload-deep':
// 重载 - 深度(参数叠加)
table.reload('test', {
where: {
abc: 123,
test: '新的 test1'
},
//defaultToolbar: ['print'], // 重载头部工具栏右侧图标
//cols: ins1.config.cols
}, true);
break;
case 'reloadData':
// 数据重载 - 参数重置
table.reloadData('test', {
where: {
abc: '123456',
//test: '新的 test2',
//token: '新的 token2'
},
scrollPos: 'fixed', // 保持滚动条位置不变 - v2.7.3 新增
height: 2000, // 测试无效参数(即与数据无关的参数设置无效,此处以 height 设置无效为例)
//url: '404',
//page: {curr: 1, limit: 30} // 重新指向分页
});
break;
case 'reloadData-deep':
// 数据重载 - 参数叠加
table.reloadData('test', {
where: {
abc: 123,
test: '新的 test1'
}
}, true);
break;
}
layer.msg('可观察 Network 请求参数的变化');
}
});
// 行模式
dropdown.render({
elem: '#rowMode',
data: [{
id: 'default-row',
title: '单行模式(默认)'
}, {
id: 'multi-row',
title: '多行模式'
}],
// 菜单被点击的事件
click: function (obj) {
var checkStatus = table.checkStatus(id)
var data = checkStatus.data; // 获取选中的数据
switch (obj.id) {
case 'default-row':
table.reload('test', {
lineStyle: null // 恢复单行
});
layer.msg('已设为单行');
break;
case 'multi-row':
table.reload('test', {
// 设置行样式,此处以设置多行高度为例。若为单行,则没必要设置改参数 - 注v2.7.0 新增
lineStyle: 'height: 95px;'
});
layer.msg('即通过设置 lineStyle 参数可开启多行');
break;
}
}
});
}, },
error: function (res, msg) { error: function (res, msg) {
console.log(res, msg) console.log(res, msg)
} }
}); });
// 工具栏事件
table.on('toolbar(test)', function (obj) {
var id = obj.config.id;
var checkStatus = table.checkStatus(id);
var othis = lay(this);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(layui.util.escape(JSON.stringify(data)));
break;
case 'getData':
var getData = table.getData(id);
console.log(getData);
layer.alert(layui.util.escape(JSON.stringify(getData)));
break;
};
});
// 表头自定义元素工具事件 --- 2.8.8+
table.on('colTool(test)', function (obj) {
var event = obj.event;
console.log(obj);
if (event === 'email-tips') {
layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
title: '当前列属性配置项'
});
}
});
// 触发单元格工具事件 function done() {
table.on('tool(test)', function (obj) { // 双击 toolDouble // 工具栏事件
var data = obj.data; // 获得当前行数据 table.on('toolbar(roomTable)', function (obj) {
// console.log(obj) var id = obj.config.id;
if (obj.event === 'edit') { var checkStatus = table.checkStatus(id);
layer.open({ var othis = lay(this);
title: '编辑 - id:' + data.id, switch (obj.event) {
type: 1, case 'getCheckData':
area: ['80%', '80%'], var data = checkStatus.data;
content: '<div style="padding: 16px;">自定义表单元素</div>' layer.alert(layui.util.escape(JSON.stringify(data)));
}); break;
} else if (obj.event === 'more') { };
// 更多 - 下拉菜单 });
dropdown.render({
elem: this, // 触发事件的 DOM 对象
show: true, // 外部事件触发即显示
data: [{
title: '查看',
id: 'detail'
}, {
title: '删除',
id: 'del'
}],
click: function (menudata) {
if (menudata.id === 'detail') {
layer.msg('查看操作,当前行 ID:' + data.id);
} else if (menudata.id === 'del') {
layer.confirm('真的删除行 [id: ' + data.id + '] 么', function (index) {
obj.del(); // 删除对应行tr的DOM结构
layer.close(index);
// 向服务端发送删除指令
});
}
},
align: 'right', // 右对齐弹出
style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
})
}
});
// 触发表格复选框选择 // 触发单元格工具事件
table.on('checkbox(test)', function (obj) { table.on('tool(roomTable)', function (obj) { // 双击 toolDouble
console.log(obj) var data = obj.data; // 获得当前行数据
}); // console.log(obj)
if (obj.event === 'edit') {
// 触发表格单选框选择 layer.open({
table.on('radio(test)', function (obj) { title: '编辑 - id:' + data.id,
console.log(obj) type: 1,
}); area: ['80%', '80%'],
content: '<div style="padding: 16px;">自定义表单元素</div>'
// 行单击事件 });
table.on('row(test)', function (obj) { } else if (obj.event === 'more') {
//console.log(obj); // 更多 - 下拉菜单
//layer.closeAll('tips'); dropdown.render({
}); elem: this, // 触发事件的 DOM 对象
// 行双击事件 show: true, // 外部事件触发即显示
table.on('rowDouble(test)', function (obj) { data: [{
console.log(obj); title: '查看',
}); id: 'detail'
}, {
// 单元格编辑事件 title: '删除',
table.on('edit(test)', function (obj) { id: 'del'
var field = obj.field; // 得到字段 }],
var value = obj.value; // 得到修改后的值 click: function (menudata) {
var data = obj.data; // 得到所在行所有键值 if (menudata.id === 'detail') {
// 值的校验 layer.msg('查看操作,当前行 ID:' + data.id);
if (field === 'email') { } else if (menudata.id === 'del') {
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(obj.value)) { layer.confirm('真的删除行 [id: ' + data.id + '] 么', function (index) {
layer.tips('输入的邮箱格式不正确,请重新编辑', this, { tips: 1 }); obj.del(); // 删除对应行tr的DOM结构
return obj.reedit(); // 重新编辑 -- v2.8.0 新增 layer.close(index);
// 向服务端发送删除指令
});
}
},
align: 'right', // 右对齐弹出
style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
})
} }
} });
// 编辑后续操作,如提交更新请求,以完成真实的数据更新 }
// …
layer.msg('编辑成功', { icon: 1 });
// 其他更新操作
var update = {};
update[field] = value;
obj.update(update);
});
}); });
</script> </script>

View File

@ -0,0 +1,106 @@
<link rel="stylesheet" href="/layui/css/layui.css">
<body>
<input id="value" value="" type="hidden" />
<form class="layui-form layui-form-pane" action="" style="padding-left: 10px;padding-right: 10px;">
<div class="layui-form-item">
<label class="layui-form-label">直播房间地址</label>
<div class="layui-input-block">
<input type="text" name="url" autocomplete="off" placeholder="https://live.bilibili.com/xxxxx"
lay-verify="required" class="layui-input">
</div>
</div>
<div class="layui-form-item" pane>
<label class="layui-form-label">录制弹幕</label>
<div class="layui-input-block">
<input type="checkbox" name="recordLive" lay-skin="switch" lay-filter="switchTest" title="启用|禁用">
</div>
</div>
<div class="layui-form-item" pane>
<label class="layui-form-label">录制视频</label>
<div class="layui-input-block">
<input type="checkbox" name="recordDanmu" lay-skin="switch" lay-filter="switchTest" title="启用|禁用">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">弹幕预定录制时间</label>
<div class="layui-input-inline">
<input type="text" name="recordDanmuDate" value="* * *" placeholder="* * *" lay-verify="required" autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-text-em" onclick="timeTips(this)"><i
class="layui-icon layui-icon-help"></i> </div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">视频预定录制时间</label>
<div class="layui-input-inline">
<input type="text" name="recordLiveDate" value="* * *" placeholder="* * *" lay-verify="required" autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-text-em" onclick="timeTips(this)"><i
class="layui-icon layui-icon-help"></i> </div>
</div>
<div class="layui-inline">
<label class="layui-form-label">录制绑定用户</label>
<div id="selects" class="layui-input-inline">
</div>
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn" lay-submit lay-filter="submit-form">确认</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</form>
</body>
<script id="selectUser" type="text/html">
<select id="recordUid" name="recordUid" lay-verify="required" lay-search>
<option value="">直接选择或搜索选择</option>
{{# layui.each(d.data, function(index, item){ }}
<option value="{{= item.uid}}">[{{=item.uid}}]{{= item.uname}}</option>
{{# }); }}
</select>
</script>
<script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script>
<script src="/js/httpUtils.js"></script>
<script>
function timeTips(that) {
layer.tips('填写[分钟][小时][星期],空格分割,例如预定每周6晚上8点之后才开始录制则填写:* 8 6', that);
}
layui.use(['form', 'laytpl'], function () {
var form = layui.form;
var layer = layui.layer;
var laytpl = layui.laytpl
// 提交事件
form.on('submit(submit-form)', function (data) {
var field = data.field; // 获取表单字段值
// 显示填写结果,仅作演示用
// 此处可执行 Ajax 等操作
// …
addRoomConfig(field)
.then(json=>{
console.log(json)
})
return false; // 阻止默认 form 跳转
});
function close(){
var index = parent.layer.getFrameIndex(window.name); // 先得到当前 iframe 层的索引
parent.layer.close(index);
}
getBiliAllUser()
.then(data => {
var view = $("#selects").get(0);
laytpl($('#selectUser').get(0).innerHTML).render(data, function (html) {
view.innerHTML=html
form.render('select');
});
})
});
</script>

View File

@ -21,14 +21,9 @@
</script> </script>
<script> <script>
function onButton(){ function onButton(){
getLiveVideoList({ getLiveVideoList()
success:function(json){ .then(data=>{
console.log(json) console.log(data)
},
error:function(error){
}
}) })
} }
</script> </script>

View File

@ -1 +1,9 @@
var headerModel=0; var headerModel=0;
function createUi(html){
return fetch(html)
.then(response=>response.text())
.then(htmlText=>{
return htmlText;
})
}

View File

@ -1,9 +1,5 @@
/** function get(url){
* return fetch(url)
* @param {*} callback 回调
*/
function getLiveVideoList(callback){
fetch("/live/video/list")
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`); throw new Error(`HTTP error! Status: ${response.status}`);
@ -11,9 +7,71 @@ function getLiveVideoList(callback){
return response.json(); return response.json();
}) })
.then(data => { .then(data => {
callback.success(data); return data;
}) })
.catch(error => { .catch(error => {
callback.error(error); return error;
}); });
} }
function post(url,formData,isJSON) {
return fetch(url, {
method: "POST",
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
if(isJSON){
return response.json();
}
return response.blob();
})
.then(blob => {
if(isJSON){
return blob;
}
const imageUrl = URL.createObjectURL(blob);
console.log("Image URL:", imageUrl);
return imageUrl;
})
.catch(error => {
console.error("There was a problem with the fetch operation:", error);
throw error; // 重新抛出错误以便外部捕获
});
}
function getLiveVideoList() {
return get("/live/video/list");
}
function getHttpImage(url) {
const encode = encodeURI(url);
const formData = new FormData();
formData.append("url", encode);
return post("/file/img",formData,false)
.then(blob=>{
return blob;
})
}
function getBiliAllUser(){
return get("/user/list")
}
function addRoomConfig(json){
const formData = new FormData();
Object.keys(json).forEach(key => {
const value = json[key];
if (Array.isArray(value)) {
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, item);
});
} else if (value !== null && typeof value === 'object') {
formData.append(key, value);
} else {
formData.append(key, value);
}
});
return post("/live/config/set",formData)
}

View File

@ -55,6 +55,35 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
return checkRecordTime(recordLiveDate); return checkRecordTime(recordLiveDate);
} }
public boolean verifyDanmuTimer() {
return verifyTimer(recordDanmuDate);
}
public boolean verifyLiveTimer() {
return verifyTimer(recordLiveDate);
}
private boolean verifyTimer(String val) {
int _length = val.length();
boolean isFullDate = (_length - val.replace("*", "").length()) == 3
&& (_length - val.replace("*", "").trim().length()) == 0;
String[] split = val.split(" ");
if (isFullDate) {
return true;
}
String minute = split[0];
String hour = split[1];
String day = split[2];
try {
Integer.parseInt(minute);
Integer.parseInt(hour);
Integer.parseInt(day);
} catch (Exception e) {
return false;
}
return true;
}
private boolean checkRecordTime(String recordDate) { private boolean checkRecordTime(String recordDate) {
int _length = recordDate.length(); int _length = recordDate.length();
boolean isFullDate = (_length - recordDate.replace("*", "").length()) == 3; boolean isFullDate = (_length - recordDate.replace("*", "").length()) == 3;
@ -70,7 +99,7 @@ public class LiveConfigDatabaseBean extends AbsDatabasesBean {
boolean isFullDay = "*".equals(day); boolean isFullDay = "*".equals(day);
Calendar today = Calendar.getInstance(); Calendar today = Calendar.getInstance();
if (!isFullDay) { if (!isFullDay) {
if (today.get(Calendar.DAY_OF_WEEK) != Integer.parseInt(day)) { if (today.get(Calendar.DAY_OF_WEEK) != Integer.parseInt(day) + 1) {
return false; return false;
} }
} }

View File

@ -1,11 +1,15 @@
package com.yutou.biliapi.databases; package com.yutou.biliapi.databases;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean; import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean; import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.login.UserInfoBean;
import com.yutou.common.databases.AbsDatabasesBean; import com.yutou.common.databases.AbsDatabasesBean;
import com.yutou.common.databases.SQLiteManager; import com.yutou.common.databases.SQLiteManager;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class BiliBiliLoginDatabase extends SQLiteManager { public class BiliBiliLoginDatabase extends SQLiteManager {
@ -52,7 +56,7 @@ public class BiliBiliLoginDatabase extends SQLiteManager {
} }
public LoginUserDatabaseBean getUser(String userId) { public LoginUserDatabaseBean getUser(String userId) {
List<LoginUserDatabaseBean> list = super.get(cookie.getTableName(), LoginUserDatabaseBean.class); List<LoginUserDatabaseBean> list = getAllUser();
if (userId == null && !list.isEmpty()) { if (userId == null && !list.isEmpty()) {
return list.getFirst(); return list.getFirst();
} }
@ -64,6 +68,16 @@ public class BiliBiliLoginDatabase extends SQLiteManager {
return null; return null;
} }
public List<LoginUserDatabaseBean> getAllUser() {
JSONArray jsonArray = super.getJSONArray(new LoginUserDatabaseBean(null).getTableName());
List<LoginUserDatabaseBean> list = new ArrayList<>();
for (Object o : jsonArray) {
JSONObject json= (JSONObject) o;
list.add(new LoginUserDatabaseBean(json.to(UserInfoBean.class)));
}
return list;
}
@Override @Override
public String getFileName() { public String getFileName() {
return "bilibili_login.db"; return "bilibili_login.db";

View File

@ -0,0 +1,34 @@
package com.yutou.bilibili.Controllers;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.bilibili.services.LiveLoginService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BiliUserController {
@Resource
LiveLoginService loginService;
@ResponseBody
@RequestMapping("/user/list")
public JSONObject getAllUser() {
JSONArray array = new JSONArray();
List<LoginUserDatabaseBean> allUser = loginService.getAllUser();
for (LoginUserDatabaseBean bean : allUser) {
JSONObject json=new JSONObject();
json.put("uid",bean.getUserInfo().getMid());
json.put("uname",bean.getUserInfo().getUname());
array.add(json);
}
return ResultData.success(array);
}
}

View File

@ -28,6 +28,17 @@ public class LiveConfigController {
@RequestMapping(value = "set", method = RequestMethod.POST) @RequestMapping(value = "set", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public JSONObject setConfig(String url, LiveConfigDatabaseBean bean) { public JSONObject setConfig(String url, LiveConfigDatabaseBean bean) {
if(!bean.verifyLiveTimer()){
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(),"房间地址/房间号错误");
}
}
LiveConfigDatabaseBean config = configService.addConfig(url, bean); LiveConfigDatabaseBean config = configService.addConfig(url, bean);
if (config != null) { if (config != null) {
return ResultData.success(config.toJson()); return ResultData.success(config.toJson());
@ -38,6 +49,13 @@ public class LiveConfigController {
@RequestMapping(value = "update", method = RequestMethod.POST) @RequestMapping(value = "update", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public JSONObject updateConfig(String roomId, LiveConfigDatabaseBean bean) { public JSONObject updateConfig(String roomId, LiveConfigDatabaseBean bean) {
if(!bean.verifyLiveTimer()){
return ResultData.fail(ReturnCode.RC999.getCode(),"视频录制时间格式错误");
}
if(!bean.verifyDanmuTimer()){
return ResultData.fail(ReturnCode.RC999.getCode(),"弹幕录制时间格式错误");
}
LiveConfigDatabaseBean config = configService.updateConfig(new BigInteger(roomId), bean); LiveConfigDatabaseBean config = configService.updateConfig(new BigInteger(roomId), bean);
if (config != null) { if (config != null) {
return ResultData.success(config.toJson()); return ResultData.success(config.toJson());

View File

@ -6,6 +6,9 @@ import com.yutou.bilibili.Tools.Tools;
import com.yutou.bilibili.datas.ResultData; import com.yutou.bilibili.datas.ResultData;
import com.yutou.bilibili.datas.VideoFilePath; import com.yutou.bilibili.datas.VideoFilePath;
import com.yutou.bilibili.services.LiveVideoService; import com.yutou.bilibili.services.LiveVideoService;
import com.yutou.common.okhttp.HttpDownloadUtils;
import com.yutou.common.utils.AppTools;
import com.yutou.common.utils.Base64Tools;
import com.yutou.common.utils.Log; import com.yutou.common.utils.Log;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
@ -15,9 +18,12 @@ import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File; import java.io.File;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
@Controller @Controller
@ -36,6 +42,7 @@ public class VideoFileController {
} }
return ResultData.success(list); return ResultData.success(list);
} }
@RequestMapping("/file/{base64}") @RequestMapping("/file/{base64}")
@ResponseBody @ResponseBody
public ResponseEntity<FileSystemResource> getFile(@PathVariable String base64) { public ResponseEntity<FileSystemResource> getFile(@PathVariable String base64) {
@ -44,4 +51,26 @@ public class VideoFileController {
return Tools.getFile(file); return Tools.getFile(file);
} }
@RequestMapping(value = "/file/img", method = RequestMethod.POST)
public ResponseEntity<FileSystemResource> getImg(String url) {
url = URLDecoder.decode(url, StandardCharsets.UTF_8);
String encode = AppTools.getMD5(url);
File img = new File("cache" + File.separator + "image" + File.separator + encode);
if (img.exists()) {
return Tools.getFile(img);
}
if (!img.getParentFile().exists()) {
img.getParentFile().mkdirs();
}
File file = HttpDownloadUtils.downloadSync(new HttpDownloadUtils.Builder()
.setFileName(encode)
.setUrl(url)
.setPath(img.getParent())
);
if (file != null) {
return Tools.getFile(file);
}
return null;
}
} }

View File

@ -72,7 +72,7 @@ public class LiveConfigService {
return database.getConfig(roomId); return database.getConfig(roomId);
} }
public File getFace(String roomId){ public File getFace(String roomId) {
LiveConfigDatabaseBean config = database.getConfig(new BigInteger(roomId)); LiveConfigDatabaseBean config = database.getConfig(new BigInteger(roomId));
if (config == null) { if (config == null) {
return null; return null;
@ -89,4 +89,23 @@ public class LiveConfigService {
); );
bean.setAnchorFace(bean.getRecordPath() + File.separator + bean.getAnchorName() + File.separator + "face.jpg"); bean.setAnchorFace(bean.getRecordPath() + File.separator + bean.getAnchorName() + File.separator + "face.jpg");
} }
public boolean checkUrl(String url) {
if (!url.startsWith("https://live.bilibili.com/")) {
try {
new BigInteger(url);
} catch (Exception e) {
return false;
}
} else {
url = url.replace("https://live.bilibili.com/", "").split("\\?")[0];
}
try {
LiveRoomInfo body = BiliLiveNetApiManager.getInstance().getApi(null).getRoomInfo(url).execute().body().getData();
return body != null;
} catch (IOException e) {
return false;
}
}
} }

View File

@ -2,15 +2,25 @@ package com.yutou.bilibili.services;
import com.yutou.biliapi.api.LoginApi; import com.yutou.biliapi.api.LoginApi;
import com.yutou.biliapi.bean.login.LoginInfoBean; 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.login.QRCodeGenerateBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliLoginNetApiManager; import com.yutou.biliapi.net.BiliLoginNetApiManager;
import com.yutou.common.okhttp.HttpBody; import com.yutou.common.okhttp.HttpBody;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service @Service
public class LiveLoginService { public class LiveLoginService {
BiliBiliLoginDatabase loginDatabase;
public LiveLoginService() {
loginDatabase = BiliBiliLoginDatabase.getInstance();
}
/** /**
* loginApi.getQRCodeGenerate().enqueue(new HttpCallback<QRCodeGenerateBean>() { * loginApi.getQRCodeGenerate().enqueue(new HttpCallback<QRCodeGenerateBean>() {
* *
@ -41,4 +51,9 @@ public class LiveLoginService {
public void login() { public void login() {
} }
public List<LoginUserDatabaseBean> getAllUser() {
return loginDatabase.getAllUser();
}
} }

View File

@ -2,6 +2,7 @@ package com.yutou.common.databases;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField; import com.alibaba.fastjson2.annotation.JSONField;
import com.alibaba.fastjson2.util.DateUtils; import com.alibaba.fastjson2.util.DateUtils;
@ -183,11 +184,57 @@ public abstract class SQLiteManager {
} }
protected JSONArray getJSONArray(String table) {
return getJSONArray(table, null);
}
protected JSONArray getJSONArray(String table, String where) {
JSONArray array = new JSONArray();
try {
Statement statement = conn.createStatement();
String sql = "SELECT * FROM `" + table + "`";
if (where != null) {
sql += " WHERE " + where;
}
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
array.add(getSQL(resultSet));
}
resultSet.close();
statement.closeOnCompletion();
} catch (Exception e) {
Log.e(e);
throw new RuntimeException(e);
}
return array;
}
private JSONObject getSQL(ResultSet resultSet) throws SQLException {
JSONObject json = new JSONObject();
for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
String name = resultSet.getMetaData().getColumnName(i + 1);
Object value = resultSet.getObject(name);
if (value instanceof String && ((String) value).startsWith("[")) {
try {
json.put(name, JSON.parseArray((String) value));
} catch (Exception e) {
json.put(name, value);
}
} else {
json.put(name, value);
if (json.get(name) == null || "null".equals(json.get(name).toString())) {
json.put(name, null);
}
}
}
return json;
}
protected <T extends AbsDatabasesBean> List<T> get(String table, Class<T> tClass) { protected <T extends AbsDatabasesBean> List<T> get(String table, Class<T> tClass) {
return get(table, null, tClass); return get(table, null, tClass);
} }
protected <T extends AbsDatabasesBean> List<T> get(String table, String where, Class<T> tClass) { protected <T extends AbsDatabasesBean> List<T> get(String table, String where, Class<T> tClass) {
List<T> list = new ArrayList<>(); List<T> list = new ArrayList<>();
try { try {
Statement statement = conn.createStatement(); Statement statement = conn.createStatement();
@ -197,24 +244,7 @@ public abstract class SQLiteManager {
} }
ResultSet resultSet = statement.executeQuery(sql); ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) { while (resultSet.next()) {
JSONObject json = new JSONObject(); list.add(getSQL(resultSet).to(tClass));
for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
String name = resultSet.getMetaData().getColumnName(i + 1);
Object value = resultSet.getObject(name);
if (value instanceof String && ((String) value).startsWith("[")) {
try {
json.put(name, JSON.parseArray((String) value));
} catch (Exception e) {
json.put(name, value);
}
} else {
json.put(name, value);
if (json.get(name) == null || "null".equals(json.get(name).toString())) {
json.put(name, null);
}
}
}
list.add(json.to(tClass));
} }
resultSet.close(); resultSet.close();
statement.closeOnCompletion(); statement.closeOnCompletion();

View File

@ -18,20 +18,7 @@ import java.util.logging.Level;
public class HttpDownloadUtils { public class HttpDownloadUtils {
public static void download(Builder builder) { public static void download(Builder builder) {
OkHttpClient okHttpClient = new OkHttpClient.Builder() createHttpClient(builder).enqueue(new Callback() {
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.build();
Request.Builder rb = new Request.Builder()
.get()
.addHeader("User-Agent", ConfigTools.getUserAgent())
.url(builder.url);
if (StringUtils.hasText(builder.cookie)) {
rb.addHeader("Set-Cookie", builder.cookie);
}
Request request = rb.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override @Override
public void onFailure(@NotNull Call call, @NotNull IOException e) { public void onFailure(@NotNull Call call, @NotNull IOException e) {
if (builder.downloadInterface != null) { if (builder.downloadInterface != null) {
@ -79,6 +66,50 @@ public class HttpDownloadUtils {
}); });
} }
public static File downloadSync(Builder builder) {
createHttpClient(builder);
try {
Response response = createHttpClient(builder).execute();
InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
File target;
if (StringUtils.hasText(builder.fileName)) {
target = new File(builder.path, builder.fileName);
} else {
target = new File(builder.path);
}
try (FileOutputStream fileOutputStream = new FileOutputStream(target)) {
byte[] buffer = new byte[2048];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
return target;
} catch (IOException e) {
Log.e("download error:" + builder.url, e);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
private static Call createHttpClient(Builder builder) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.build();
Request.Builder rb = new Request.Builder()
.get()
.addHeader("User-Agent", ConfigTools.getUserAgent())
.url(builder.url);
if (StringUtils.hasText(builder.cookie)) {
rb.addHeader("Set-Cookie", builder.cookie);
}
Request request = rb.build();
return okHttpClient.newCall(request);
}
@Data @Data
public static class Builder { public static class Builder {
String url; String url;