定时犇犇来了!
_DEQUE_
·
·
个人记录
// ==UserScript==
// @name 洛谷定时发布犇犇
// @namespace http://tampermonkey.net/
// @version 1.0.0
// @description 在洛谷中支持定时发布犇犇(动态),可设定未来任意时间自动发布
// @author Assistant
// @match https://www.luogu.com.cn/*
// @match https://www.luogu.com.cn/feed/benben
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_notification
// @connect www.luogu.com.cn
// @run-at document-end
// @license MIT
// ==/UserScript==
(function() {
'use strict';
// 存储定时任务的key前缀
const STORAGE_PREFIX = 'luogu_benben_timer_';
// 已加载标记
let initialized = false;
// 检查定时器的间隔(毫秒)
const CHECK_INTERVAL = 30000; // 30秒检查一次
let checkIntervalId = null;
// 获取当前用户ID(用于确保任务归属)
function getCurrentUserId() {
// 尝试从页面全局变量中获取用户信息
try {
// 常见模式:window._feInjection.currentUser.uid
if (window._feInjection && window._feInjection.currentUser && window._feInjection.currentUser.uid) {
return window._feInjection.currentUser.uid;
}
// 尝试从localStorage中解析
const userStr = localStorage.getItem('user');
if (userStr) {
const user = JSON.parse(userStr);
if (user && user.uid) return user.uid;
}
} catch(e) {}
return 'unknown';
}
// 保存定时任务
function saveTask(taskId, taskData) {
GM_setValue(STORAGE_PREFIX + taskId, JSON.stringify(taskData));
}
// 获取所有定时任务
function getAllTasks() {
const tasks = [];
const keys = GM_listValues();
for (const key of keys) {
if (key.startsWith(STORAGE_PREFIX)) {
try {
const taskData = JSON.parse(GM_getValue(key, '{}'));
const taskId = key.substring(STORAGE_PREFIX.length);
tasks.push({ id: taskId, ...taskData });
} catch(e) {}
}
}
return tasks;
}
// 删除任务
function deleteTask(taskId) {
GM_deleteValue(STORAGE_PREFIX + taskId);
}
// 实际发布犇犇
async function publishBenben(content) {
try {
const token = getCsrfToken();
if (!token) {
console.error('[定时犇犇] 无法获取CSRF Token');
GM_notification({
title: '定时发布失败',
text: '无法获取CSRF Token,请刷新页面重试',
timeout: 5000
});
return false;
}
const response = await fetch('https://www.luogu.com.cn/api/feed/postBenben', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token,
'Referer': 'https://www.luogu.com.cn/',
'Origin': 'https://www.luogu.com.cn'
},
credentials: 'include',
body: JSON.stringify({ content: content })
});
const data = await response.json();
if (data.status === 200 || data.code === 200) {
console.log('[定时犇犇] 发布成功:', content);
GM_notification({
title: '定时犇犇发布成功',
text: content.length > 30 ? content.substring(0,30)+'...' : content,
timeout: 5000
});
return true;
} else {
console.error('[定时犇犇] 发布失败:', data);
GM_notification({
title: '定时发布失败',
text: data.message || '未知错误',
timeout: 5000
});
return false;
}
} catch(err) {
console.error('[定时犇犇] 请求异常:', err);
GM_notification({
title: '定时发布失败',
text: err.message || '网络错误',
timeout: 5000
});
return false;
}
}
// 获取CSRF Token(洛谷使用)
function getCsrfToken() {
// 方法1: 从meta标签
const meta = document.querySelector('meta[name="csrf-token"]');
if (meta && meta.getAttribute('content')) {
return meta.getAttribute('content');
}
// 方法2: 从cookie中获取
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [name, value] = cookie.trim().split('=');
if (name === 'csrf_token' || name === 'XSRF-TOKEN') {
return decodeURIComponent(value);
}
}
// 方法3: 从全局window对象
if (window.csrfToken) return window.csrfToken;
if (window._csrf) return window._csrf;
return null;
}
// 检查并执行到期的定时任务
async function checkAndExecuteTasks() {
const tasks = getAllTasks();
const now = Date.now();
let hasChanges = false;
for (const task of tasks) {
if (task.publishTime <= now) {
// 任务到期,执行发布
console.log('[定时犇犇] 执行到期任务:', task.id);
await publishBenben(task.content);
deleteTask(task.id);
hasChanges = true;
}
}
if (hasChanges && window.updateTimerListUI) {
window.updateTimerListUI();
}
}
// 添加定时任务
function addTimerTask(datetime, content) {
const publishTime = new Date(datetime).getTime();
if (isNaN(publishTime)) {
alert('日期格式无效');
return false;
}
if (publishTime <= Date.now()) {
alert('请选择未来的时间');
return false;
}
if (!content.trim()) {
alert('内容不能为空');
return false;
}
const taskId = Date.now() + '_' + Math.random().toString(36).substr(2, 8);
const userId = getCurrentUserId();
const taskData = {
content: content,
publishTime: publishTime,
createTime: Date.now(),
userId: userId,
datetimeStr: new Date(publishTime).toLocaleString()
};
saveTask(taskId, taskData);
if (window.updateTimerListUI) window.updateTimerListUI();
alert(`定时发布已设置!将在 ${taskData.datetimeStr} 发布`);
return true;
}
// 创建定时器的UI面板(浮动窗口)
function createTimerPanel() {
// 检查是否已存在
if (document.getElementById('luogu-benben-timer-panel')) return;
const panel = document.createElement('div');
panel.id = 'luogu-benben-timer-panel';
panel.innerHTML = `
<style>
#luogu-benben-timer-panel {
position: fixed;
bottom: 80px;
right: 20px;
width: 320px;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
z-index: 10000;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 14px;
border: 1px solid #e0e0e0;
transition: all 0.3s ease;
}
#luogu-benben-timer-panel .panel-header {
padding: 12px 15px;
background: #3498db;
color: white;
border-radius: 12px 12px 0 0;
cursor: move;
display: flex;
justify-content: space-between;
align-items: center;
}
#luogu-benben-timer-panel .panel-header h3 {
margin: 0;
font-size: 16px;
font-weight: 500;
}
#luogu-benben-timer-panel .panel-header .close-btn {
cursor: pointer;
font-size: 20px;
line-height: 1;
background: none;
border: none;
color: white;
opacity: 0.8;
}
#luogu-benben-timer-panel .panel-header .close-btn:hover { opacity: 1; }
#luogu-benben-timer-panel .panel-content {
padding: 15px;
}
#luogu-benben-timer-panel .form-group {
margin-bottom: 12px;
}
#luogu-benben-timer-panel label {
display: block;
margin-bottom: 5px;
font-weight: 500;
color: #333;
}
#luogu-benben-timer-panel input, #luogu-benben-timer-panel textarea {
width: 100%;
padding: 8px 10px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 13px;
box-sizing: border-box;
}
#luogu-benben-timer-panel textarea {
resize: vertical;
min-height: 70px;
}
#luogu-benben-timer-panel button {
background: #3498db;
color: white;
border: none;
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
width: 100%;
}
#luogu-benben-timer-panel button:hover {
background: #2980b9;
}
#luogu-benben-timer-panel .task-list {
margin-top: 15px;
border-top: 1px solid #eee;
padding-top: 10px;
max-height: 200px;
overflow-y: auto;
}
#luogu-benben-timer-panel .task-item {
background: #f9f9f9;
border-radius: 6px;
padding: 8px;
margin-bottom: 8px;
font-size: 12px;
position: relative;
}
#luogu-benben-timer-panel .task-time {
color: #e67e22;
font-size: 11px;
margin-bottom: 4px;
}
#luogu-benben-timer-panel .task-content {
color: #555;
word-break: break-all;
padding-right: 50px;
}
#luogu-benben-timer-panel .delete-task {
position: absolute;
right: 8px;
top: 8px;
background: #e74c3c;
color: white;
border: none;
border-radius: 4px;
padding: 2px 8px;
font-size: 11px;
cursor: pointer;
}
#luogu-benben-timer-panel .delete-task:hover {
background: #c0392b;
}
#luogu-benben-timer-panel .empty-tip {
color: #999;
text-align: center;
padding: 10px;
font-size: 12px;
}
</style>
<div class="panel-header">
<h3>📅 定时犇犇发布器</h3>
<button class="close-btn" id="timer-panel-close">×</button>
</div>
<div class="panel-content">
<div class="form-group">
<label>发布时间</label>
<input type="datetime-local" id="timer-datetime" step="1">
</div>
<div class="form-group">
<label>犇犇内容</label>
<textarea id="timer-content" placeholder="写点什么..."></textarea>
</div>
<button id="add-timer-btn">⏰ 添加定时发布</button>
<div class="task-list">
<div style="margin: 5px 0 8px 0; font-weight:500;">📋 待发布列表</div>
<div id="timer-task-list"></div>
</div>
</div>
`;
document.body.appendChild(panel);
// 绑定事件
const closeBtn = panel.querySelector('#timer-panel-close');
closeBtn.addEventListener('click', () => {
panel.style.display = 'none';
});
const addBtn = panel.querySelector('#add-timer-btn');
addBtn.addEventListener('click', () => {
const datetimeInput = panel.querySelector('#timer-datetime');
const contentInput = panel.querySelector('#timer-content');
addTimerTask(datetimeInput.value, contentInput.value);
if (datetimeInput.value && contentInput.value) {
contentInput.value = '';
// 不清空时间,方便连续添加
}
});
// 拖动功能
makeDraggable(panel);
// 渲染任务列表
window.updateTimerListUI = function() {
const tasks = getAllTasks();
const container = panel.querySelector('#timer-task-list');
if (!container) return;
if (tasks.length === 0) {
container.innerHTML = '<div class="empty-tip">暂无定时任务</div>';
return;
}
// 按发布时间排序
tasks.sort((a,b) => a.publishTime - b.publishTime);
let html = '';
for (const task of tasks) {
const timeStr = new Date(task.publishTime).toLocaleString();
const contentPreview = task.content.length > 40 ? task.content.substring(0,40)+'...' : task.content;
html += `
<div class="task-item" data-id="${task.id}">
<div class="task-time">🕒 ${timeStr}</div>
<div class="task-content">${escapeHtml(contentPreview)}</div>
<button class="delete-task" data-id="${task.id}">删除</button>
</div>
`;
}
container.innerHTML = html;
// 绑定删除按钮事件
container.querySelectorAll('.delete-task').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const taskId = btn.getAttribute('data-id');
if (confirm('确定删除这个定时任务吗?')) {
deleteTask(taskId);
window.updateTimerListUI();
}
});
});
};
// 初始渲染
window.updateTimerListUI();
}
// 简单的HTML转义
function escapeHtml(str) {
return str.replace(/[&<>]/g, function(m) {
if (m === '&') return '&';
if (m === '<') return '<';
if (m === '>') return '>';
return m;
});
}
// 使面板可拖动
function makeDraggable(element) {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
const header = element.querySelector('.panel-header');
if (!header) return;
header.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
let top = element.offsetTop - pos2;
let left = element.offsetLeft - pos1;
if (top < 0) top = 0;
if (left < 0) left = 0;
if (left + element.offsetWidth > window.innerWidth) left = window.innerWidth - element.offsetWidth;
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.bottom = 'auto';
element.style.right = 'auto';
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
// 在犇犇页面添加一个快捷按钮(浮动按钮显示/隐藏面板)
function addToggleButton() {
if (document.getElementById('luogu-timer-toggle-btn')) return;
const btn = document.createElement('div');
btn.id = 'luogu-timer-toggle-btn';
btn.innerHTML = '📅 定时犇犇';
btn.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
background: #3498db;
color: white;
padding: 10px 16px;
border-radius: 30px;
font-size: 14px;
font-family: sans-serif;
cursor: pointer;
z-index: 9999;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
font-weight: 500;
`;
btn.onclick = () => {
const panel = document.getElementById('luogu-benben-timer-panel');
if (panel) {
if (panel.style.display === 'none') {
panel.style.display = 'block';
} else {
panel.style.display = 'none';
}
} else {
createTimerPanel();
}
};
document.body.appendChild(btn);
}
// 初始化定时检查器
function initTimerChecker() {
if (checkIntervalId) clearInterval(checkIntervalId);
checkIntervalId = setInterval(() => {
checkAndExecuteTasks();
}, CHECK_INTERVAL);
// 立即检查一次
setTimeout(() => checkAndExecuteTasks(), 3000);
}
// 主入口
function main() {
if (initialized) return;
initialized = true;
// 仅当用户已登录且页面准备就绪时显示功能
const waitForUser = setInterval(() => {
const userId = getCurrentUserId();
if (userId !== 'unknown') {
clearInterval(waitForUser);
// 用户已登录,初始化所有功能
createTimerPanel();
addToggleButton();
initTimerChecker();
console.log('[定时犇犇] 脚本已启动,用户ID:', userId);
// 可选:将面板初始隐藏,点击按钮再显示
const panel = document.getElementById('luogu-benben-timer-panel');
if (panel) panel.style.display = 'none';
}
}, 1000);
// 5秒后如果还未检测到用户,也尝试初始化(可能未登录,但仍提供UI,只是发布时会失败)
setTimeout(() => {
clearInterval(waitForUser);
if (!initialized) return;
if (!document.getElementById('luogu-benben-timer-panel')) {
createTimerPanel();
addToggleButton();
initTimerChecker();
const panel = document.getElementById('luogu-benben-timer-panel');
if (panel) panel.style.display = 'none';
console.log('[定时犇犇] 未检测到用户登录,以访客模式运行(发布需要登录)');
}
}, 5000);
}
// 等待页面加载完成
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', main);
} else {
main();
}
})();