Initial commit: lottery project structure
Add core project files including: - Client and server directories - Backup script - Package configuration - Git ignore rules Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@@ -0,0 +1,44 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
|
||||
const db = new Database(path.join(__dirname, 'lottery.db'));
|
||||
|
||||
// 初始化表结构
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
game TEXT NOT NULL,
|
||||
issue TEXT,
|
||||
numbers TEXT,
|
||||
bet_count INTEGER DEFAULT 1,
|
||||
multiple INTEGER DEFAULT 1,
|
||||
is_additional INTEGER DEFAULT 0,
|
||||
cost REAL NOT NULL,
|
||||
prize REAL DEFAULT 0,
|
||||
status TEXT DEFAULT 'pending',
|
||||
image_path TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS lottery_results (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
game TEXT NOT NULL,
|
||||
issue TEXT NOT NULL,
|
||||
numbers TEXT NOT NULL,
|
||||
draw_date DATE,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(game, issue)
|
||||
);
|
||||
`);
|
||||
|
||||
module.exports = db;
|
||||
@@ -0,0 +1,43 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
|
||||
// 初始化数据库
|
||||
require('./db/init');
|
||||
|
||||
const authRoutes = require('./routes/auth');
|
||||
const ticketRoutes = require('./routes/tickets');
|
||||
const lotteryRoutes = require('./routes/lottery');
|
||||
const ocrRoutes = require('./routes/ocr');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 4444;
|
||||
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
|
||||
|
||||
// API 路由
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/tickets', ticketRoutes);
|
||||
app.use('/api/lottery', lotteryRoutes);
|
||||
app.use('/api/ocr', ocrRoutes);
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (req, res) => {
|
||||
res.json({ status: 'ok', time: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// 静态文件服务 - 前端构建产物
|
||||
const clientDist = path.join(__dirname, '../client/dist');
|
||||
app.use(express.static(clientDist));
|
||||
|
||||
// SPA 路由 - 所有非 API 请求返回 index.html
|
||||
app.get('*', (req, res) => {
|
||||
res.sendFile(path.join(clientDist, 'index.html'));
|
||||
});
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`服务器运行在 http://0.0.0.0:${PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'lottery-secret-key-change-in-production';
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: '未登录' });
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: 'token无效' });
|
||||
}
|
||||
}
|
||||
|
||||
function generateToken(user) {
|
||||
return jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '7d' });
|
||||
}
|
||||
|
||||
module.exports = { authMiddleware, generateToken, JWT_SECRET };
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "lottery-server",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"dev": "nodemon index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"cors": "^2.8.5",
|
||||
"better-sqlite3": "^9.4.3",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"tesseract.js": "^5.0.4",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const db = require('../db/init');
|
||||
const { generateToken } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 注册
|
||||
router.post('/register', (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: '用户名和密码不能为空' });
|
||||
}
|
||||
|
||||
try {
|
||||
const hashedPassword = bcrypt.hashSync(password, 10);
|
||||
const stmt = db.prepare('INSERT INTO users (username, password) VALUES (?, ?)');
|
||||
const result = stmt.run(username, hashedPassword);
|
||||
|
||||
const user = { id: result.lastInsertRowid, username };
|
||||
const token = generateToken(user);
|
||||
|
||||
res.json({ user, token });
|
||||
} catch (err) {
|
||||
if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
||||
return res.status(400).json({ error: '用户名已存在' });
|
||||
}
|
||||
res.status(500).json({ error: '注册失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 登录
|
||||
router.post('/login', (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: '用户名和密码不能为空' });
|
||||
}
|
||||
|
||||
const stmt = db.prepare('SELECT * FROM users WHERE username = ?');
|
||||
const user = stmt.get(username);
|
||||
|
||||
if (!user || !bcrypt.compareSync(password, user.password)) {
|
||||
return res.status(401).json({ error: '用户名或密码错误' });
|
||||
}
|
||||
|
||||
const token = generateToken(user);
|
||||
res.json({ user: { id: user.id, username: user.username }, token });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,65 @@
|
||||
const express = require('express');
|
||||
const db = require('../db/init');
|
||||
const { authMiddleware } = require('../middleware/auth');
|
||||
const { fetchLotteryResult, updateTicketsStatus, getEstimatedDrawTime } = require('../services/lottery');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
// 查询开奖结果
|
||||
router.get('/result', async (req, res) => {
|
||||
const { game, issue } = req.query;
|
||||
|
||||
if (!game || !issue) {
|
||||
return res.status(400).json({ error: '请提供彩票类型和期号' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fetchLotteryResult(game, issue);
|
||||
if (result) {
|
||||
res.json(result);
|
||||
} else {
|
||||
// 未开奖时返回预计开奖时间
|
||||
const estimatedTime = getEstimatedDrawTime(game, issue);
|
||||
res.json({
|
||||
message: '暂未开奖或未找到数据',
|
||||
drawn: false,
|
||||
estimated_draw_time: estimatedTime
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '查询失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 刷新用户所有待开奖彩票状态
|
||||
router.post('/refresh', async (req, res) => {
|
||||
try {
|
||||
await updateTicketsStatus(req.user.id);
|
||||
res.json({ message: '刷新成功' });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '刷新失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取最近开奖记录
|
||||
router.get('/recent', async (req, res) => {
|
||||
const { game, limit = 10 } = req.query;
|
||||
|
||||
let query = 'SELECT * FROM lottery_results';
|
||||
const params = [];
|
||||
|
||||
if (game) {
|
||||
query += ' WHERE game = ?';
|
||||
params.push(game);
|
||||
}
|
||||
|
||||
query += ' ORDER BY draw_date DESC LIMIT ?';
|
||||
params.push(Number(limit));
|
||||
|
||||
const results = db.prepare(query).all(...params);
|
||||
res.json(results.map(r => ({ ...r, numbers: JSON.parse(r.numbers) })));
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,54 @@
|
||||
const express = require('express');
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { authMiddleware } = require('../middleware/auth');
|
||||
const { parseTicketImage } = require('../services/ocr');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 配置文件上传
|
||||
const uploadDir = path.join(__dirname, '../uploads');
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => cb(null, uploadDir),
|
||||
filename: (req, file, cb) => {
|
||||
const ext = path.extname(file.originalname);
|
||||
cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`);
|
||||
}
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: 10 * 1024 * 1024 },
|
||||
fileFilter: (req, file, cb) => {
|
||||
// 放宽图片类型限制
|
||||
if (file.mimetype.startsWith('image/')) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('只支持图片文件'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
// 上传并解析彩票图片
|
||||
router.post('/parse', upload.single('image'), async (req, res) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: '请上传图片' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await parseTicketImage(req.file.path);
|
||||
result.image_path = `/uploads/${req.file.filename}`;
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message || '解析失败' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,138 @@
|
||||
const express = require('express');
|
||||
const db = require('../db/init');
|
||||
const { authMiddleware } = require('../middleware/auth');
|
||||
const { getEstimatedDrawTime } = require('../services/lottery');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
// 获取彩票列表
|
||||
router.get('/', (req, res) => {
|
||||
const { page = 1, limit = 20 } = req.query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const tickets = db.prepare(`
|
||||
SELECT * FROM tickets WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?
|
||||
`).all(req.user.id, limit, offset);
|
||||
|
||||
// 为未开奖彩票添加预计开奖时间
|
||||
const ticketsWithDrawTime = tickets.map(ticket => {
|
||||
if (ticket.status === 'pending' && ticket.game && ticket.issue) {
|
||||
return {
|
||||
...ticket,
|
||||
estimated_draw_time: getEstimatedDrawTime(ticket.game, ticket.issue)
|
||||
};
|
||||
}
|
||||
return ticket;
|
||||
});
|
||||
|
||||
const total = db.prepare('SELECT COUNT(*) as count FROM tickets WHERE user_id = ?').get(req.user.id);
|
||||
|
||||
res.json({ tickets: ticketsWithDrawTime, total: total.count, page: Number(page), limit: Number(limit) });
|
||||
});
|
||||
|
||||
// 获取统计数据
|
||||
router.get('/stats', (req, res) => {
|
||||
const stats = db.prepare(`
|
||||
SELECT
|
||||
COALESCE(SUM(cost), 0) as total_cost,
|
||||
COALESCE(SUM(prize), 0) as total_prize,
|
||||
COUNT(*) as total_tickets,
|
||||
SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END) as won_count,
|
||||
SUM(CASE WHEN status = 'lost' THEN 1 ELSE 0 END) as lost_count,
|
||||
SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count
|
||||
FROM tickets WHERE user_id = ?
|
||||
`).get(req.user.id);
|
||||
|
||||
res.json({
|
||||
totalCost: stats.total_cost,
|
||||
totalPrize: stats.total_prize,
|
||||
netIncome: stats.total_prize - stats.total_cost,
|
||||
totalTickets: stats.total_tickets,
|
||||
wonCount: stats.won_count || 0,
|
||||
lostCount: stats.lost_count || 0,
|
||||
pendingCount: stats.pending_count || 0
|
||||
});
|
||||
});
|
||||
|
||||
// 添加彩票
|
||||
router.post('/', (req, res) => {
|
||||
const { type, game, issue, numbers, bet_count, multiple, is_additional, cost, image_path } = req.body;
|
||||
|
||||
if (!type || !game || !cost) {
|
||||
return res.status(400).json({ error: '缺少必要字段' });
|
||||
}
|
||||
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO tickets (user_id, type, game, issue, numbers, bet_count, multiple, is_additional, cost, image_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const result = stmt.run(
|
||||
req.user.id, type, game, issue || null,
|
||||
numbers ? JSON.stringify(numbers) : null,
|
||||
bet_count || 1, multiple || 1, is_additional ? 1 : 0, cost, image_path || null
|
||||
);
|
||||
|
||||
res.json({ id: result.lastInsertRowid, message: '添加成功' });
|
||||
});
|
||||
|
||||
// 更新彩票
|
||||
router.put('/:id', (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { type, game, issue, numbers, bet_count, multiple, is_additional, cost, prize, status } = req.body;
|
||||
|
||||
const ticket = db.prepare('SELECT * FROM tickets WHERE id = ? AND user_id = ?').get(id, req.user.id);
|
||||
if (!ticket) {
|
||||
return res.status(404).json({ error: '彩票不存在' });
|
||||
}
|
||||
|
||||
const stmt = db.prepare(`
|
||||
UPDATE tickets SET type = ?, game = ?, issue = ?, numbers = ?, bet_count = ?, multiple = ?, is_additional = ?, cost = ?, prize = ?, status = ?
|
||||
WHERE id = ?
|
||||
`);
|
||||
stmt.run(
|
||||
type ?? ticket.type,
|
||||
game ?? ticket.game,
|
||||
issue !== undefined ? issue : ticket.issue,
|
||||
numbers ? JSON.stringify(numbers) : ticket.numbers,
|
||||
bet_count ?? ticket.bet_count,
|
||||
multiple ?? ticket.multiple,
|
||||
is_additional !== undefined ? (is_additional ? 1 : 0) : ticket.is_additional,
|
||||
cost ?? ticket.cost,
|
||||
prize ?? ticket.prize,
|
||||
status ?? ticket.status,
|
||||
id
|
||||
);
|
||||
|
||||
res.json({ message: '更新成功' });
|
||||
});
|
||||
|
||||
// 删除彩票
|
||||
router.delete('/:id', (req, res) => {
|
||||
const { id } = req.params;
|
||||
const ticketId = Number(id);
|
||||
|
||||
console.log('删除请求:', { id, ticketId, userId: req.user.id });
|
||||
|
||||
if (isNaN(ticketId)) {
|
||||
return res.status(400).json({ error: '无效的ID' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = db.prepare('DELETE FROM tickets WHERE id = ? AND user_id = ?').run(ticketId, req.user.id);
|
||||
console.log('删除结果:', result);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: '彩票不存在' });
|
||||
}
|
||||
|
||||
res.json({ message: '删除成功' });
|
||||
} catch (err) {
|
||||
console.error('删除错误:', err);
|
||||
res.status(500).json({ error: '删除失败: ' + err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,250 @@
|
||||
const axios = require('axios');
|
||||
const cheerio = require('cheerio');
|
||||
const db = require('../db/init');
|
||||
|
||||
// 获取预计开奖时间
|
||||
function getEstimatedDrawTime(game, issue) {
|
||||
const now = new Date();
|
||||
const currentDay = now.getDay();
|
||||
const currentHour = now.getHours();
|
||||
const currentMinute = now.getMinutes();
|
||||
|
||||
let drawDays = []; // 开奖日期(周日=0,周一=1...)
|
||||
|
||||
if (game === '双色球') {
|
||||
drawDays = [2, 4, 0]; // 周二、周四、周日
|
||||
} else if (game === '大乐透') {
|
||||
drawDays = [1, 3, 5]; // 周一、周三、周六
|
||||
}
|
||||
|
||||
if (drawDays.length === 0) return null;
|
||||
|
||||
// 按日期排序
|
||||
drawDays.sort((a, b) => a - b);
|
||||
|
||||
// 找到最近的下一个开奖日
|
||||
let daysUntilDraw = -1;
|
||||
for (const day of drawDays) {
|
||||
if (day > currentDay) {
|
||||
daysUntilDraw = day - currentDay;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果今天就是开奖日,检查是否已过开奖时间
|
||||
if (daysUntilDraw === -1) {
|
||||
// 没有找到更晚的日期,循环回到第一个开奖日
|
||||
daysUntilDraw = (drawDays[0] + 7) - currentDay;
|
||||
} else if (daysUntilDraw === 0) {
|
||||
// 今天是开奖日,检查是否已过21:15
|
||||
if (currentHour > 21 || (currentHour === 21 && currentMinute >= 15)) {
|
||||
daysUntilDraw = (drawDays[0] + 7) - currentDay;
|
||||
}
|
||||
}
|
||||
|
||||
const nextDraw = new Date(now);
|
||||
nextDraw.setDate(now.getDate() + daysUntilDraw);
|
||||
nextDraw.setHours(21, 15, 0, 0);
|
||||
|
||||
return nextDraw.toISOString();
|
||||
}
|
||||
|
||||
// 获取开奖结果
|
||||
async function fetchLotteryResult(game, issue) {
|
||||
// 先查本地缓存
|
||||
const cached = db.prepare('SELECT * FROM lottery_results WHERE game = ? AND issue = ?').get(game, issue);
|
||||
if (cached) {
|
||||
return { ...cached, numbers: JSON.parse(cached.numbers) };
|
||||
}
|
||||
|
||||
// 从网络获取
|
||||
try {
|
||||
const result = await fetchFromWeb(game, issue);
|
||||
if (result) {
|
||||
// 缓存到数据库
|
||||
db.prepare(`
|
||||
INSERT OR REPLACE INTO lottery_results (game, issue, numbers, draw_date)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`).run(game, issue, JSON.stringify(result.numbers), result.draw_date);
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.error('获取开奖数据失败:', err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 从500.com获取数据
|
||||
async function fetchFromWeb(game, issue) {
|
||||
try {
|
||||
if (game === '双色球') {
|
||||
return await fetchSSQ(issue);
|
||||
} else if (game === '大乐透') {
|
||||
return await fetchDLT(issue);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`获取${game}开奖数据失败:`, err.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 获取双色球开奖数据
|
||||
async function fetchSSQ(issue) {
|
||||
const url = 'https://datachart.500.com/ssq/history/newinc/history.php?limit=50';
|
||||
const response = await axios.get(url, {
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' },
|
||||
timeout: 10000
|
||||
});
|
||||
|
||||
const $ = cheerio.load(response.data);
|
||||
let result = null;
|
||||
|
||||
// 处理期号格式:2026019 -> 26019 或 26019 -> 26019
|
||||
const shortIssue = issue.length > 5 ? issue.slice(-5) : issue;
|
||||
|
||||
$('#tdata tr').each((i, row) => {
|
||||
const tds = $(row).find('td');
|
||||
const rowIssue = $(tds[0]).text().trim();
|
||||
|
||||
if (rowIssue === shortIssue || rowIssue === issue) {
|
||||
const red = [];
|
||||
for (let j = 1; j <= 6; j++) {
|
||||
red.push($(tds[j]).text().trim());
|
||||
}
|
||||
const blue = $(tds[7]).text().trim();
|
||||
const drawDate = $(tds[15]).text().trim();
|
||||
|
||||
result = {
|
||||
game: '双色球',
|
||||
issue: issue, // 返回原始期号
|
||||
numbers: { red, blue },
|
||||
draw_date: drawDate
|
||||
};
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 获取大乐透开奖数据
|
||||
async function fetchDLT(issue) {
|
||||
const url = 'https://datachart.500.com/dlt/history/newinc/history.php?limit=50';
|
||||
const response = await axios.get(url, {
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' },
|
||||
timeout: 10000
|
||||
});
|
||||
|
||||
const $ = cheerio.load(response.data);
|
||||
let result = null;
|
||||
|
||||
// 处理期号格式:2026019 -> 26019 或 26019 -> 26019
|
||||
const shortIssue = issue.length > 5 ? issue.slice(-5) : issue;
|
||||
|
||||
$('#tdata tr').each((i, row) => {
|
||||
const tds = $(row).find('td');
|
||||
const rowIssue = $(tds[0]).text().trim();
|
||||
|
||||
if (rowIssue === shortIssue || rowIssue === issue) {
|
||||
const front = [];
|
||||
for (let j = 1; j <= 5; j++) {
|
||||
front.push($(tds[j]).text().trim());
|
||||
}
|
||||
const back = [];
|
||||
for (let j = 6; j <= 7; j++) {
|
||||
back.push($(tds[j]).text().trim());
|
||||
}
|
||||
const drawDate = $(tds[14]).text().trim();
|
||||
|
||||
result = {
|
||||
game: '大乐透',
|
||||
issue: issue, // 返回原始期号
|
||||
numbers: { front, back },
|
||||
draw_date: drawDate
|
||||
};
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 检查中奖
|
||||
function checkWinning(game, ticketNumbers, resultNumbers) {
|
||||
if (!ticketNumbers || !resultNumbers) return { won: false, prize: 0 };
|
||||
|
||||
if (game === '双色球') {
|
||||
return checkSSQWinning(ticketNumbers, resultNumbers);
|
||||
} else if (game === '大乐透') {
|
||||
return checkDLTWinning(ticketNumbers, resultNumbers);
|
||||
}
|
||||
|
||||
return { won: false, prize: 0 };
|
||||
}
|
||||
|
||||
// 双色球中奖检查
|
||||
function checkSSQWinning(ticket, result) {
|
||||
const redMatch = ticket.red.filter(n => result.red.includes(n)).length;
|
||||
const blueMatch = ticket.blue === result.blue;
|
||||
|
||||
if (redMatch === 6 && blueMatch) return { won: true, level: 1, prize: 5000000 };
|
||||
if (redMatch === 6) return { won: true, level: 2, prize: 100000 };
|
||||
if (redMatch === 5 && blueMatch) return { won: true, level: 3, prize: 3000 };
|
||||
if (redMatch === 5 || (redMatch === 4 && blueMatch)) return { won: true, level: 4, prize: 200 };
|
||||
if (redMatch === 4 || (redMatch === 3 && blueMatch)) return { won: true, level: 5, prize: 10 };
|
||||
if (blueMatch) return { won: true, level: 6, prize: 5 };
|
||||
|
||||
return { won: false, prize: 0 };
|
||||
}
|
||||
|
||||
// 大乐透中奖检查
|
||||
function checkDLTWinning(ticket, result) {
|
||||
const frontMatch = ticket.front.filter(n => result.front.includes(n)).length;
|
||||
const backMatch = ticket.back.filter(n => result.back.includes(n)).length;
|
||||
|
||||
if (frontMatch === 5 && backMatch === 2) return { won: true, level: 1, prize: 10000000 };
|
||||
if (frontMatch === 5 && backMatch === 1) return { won: true, level: 2, prize: 100000 };
|
||||
if (frontMatch === 5) return { won: true, level: 3, prize: 10000 };
|
||||
if (frontMatch === 4 && backMatch === 2) return { won: true, level: 4, prize: 3000 };
|
||||
if (frontMatch === 4 && backMatch === 1) return { won: true, level: 5, prize: 300 };
|
||||
if (frontMatch === 3 && backMatch === 2) return { won: true, level: 6, prize: 200 };
|
||||
if (frontMatch === 4) return { won: true, level: 7, prize: 100 };
|
||||
// 8等奖:3+1 或 2+2,15元
|
||||
if ((frontMatch === 3 && backMatch === 1) || (frontMatch === 2 && backMatch === 2)) return { won: true, level: 8, prize: 15 };
|
||||
// 9等奖:3+0 或 2+1 或 1+2 或 后区2个,5元
|
||||
if (frontMatch === 3 || (frontMatch === 2 && backMatch === 1) || (frontMatch === 1 && backMatch === 2) || backMatch === 2) return { won: true, level: 9, prize: 5 };
|
||||
|
||||
return { won: false, prize: 0 };
|
||||
}
|
||||
|
||||
// 批量更新彩票状态
|
||||
async function updateTicketsStatus(userId) {
|
||||
const pendingTickets = db.prepare(`
|
||||
SELECT * FROM tickets WHERE user_id = ? AND status = 'pending' AND issue IS NOT NULL
|
||||
`).all(userId);
|
||||
|
||||
for (const ticket of pendingTickets) {
|
||||
const result = await fetchLotteryResult(ticket.game, ticket.issue);
|
||||
if (result) {
|
||||
const ticketNumbers = ticket.numbers ? JSON.parse(ticket.numbers) : null;
|
||||
if (ticketNumbers && ticketNumbers.length > 0) {
|
||||
let totalPrize = 0;
|
||||
for (const num of ticketNumbers) {
|
||||
const winning = checkWinning(ticket.game, num, result.numbers);
|
||||
if (winning.won) {
|
||||
totalPrize += winning.prize * ticket.multiple;
|
||||
// 大乐透只有1等奖和2等奖追加才有80%浮动奖金,其他等级没有
|
||||
if (ticket.is_additional && winning.level >= 1 && winning.level <= 2) {
|
||||
totalPrize += Math.floor(winning.prize * 0.8) * ticket.multiple;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
db.prepare('UPDATE tickets SET prize = ?, status = ? WHERE id = ?')
|
||||
.run(totalPrize, totalPrize > 0 ? 'won' : 'lost', ticket.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { fetchLotteryResult, checkWinning, updateTicketsStatus, getEstimatedDrawTime };
|
||||
@@ -0,0 +1,207 @@
|
||||
const Tesseract = require('tesseract.js');
|
||||
const path = require('path');
|
||||
|
||||
// 彩票类型识别规则
|
||||
const LOTTERY_PATTERNS = {
|
||||
// 福利彩票
|
||||
ssq: { name: '双色球', type: 'welfare', pattern: /双\s*色\s*球|SSQ/i, price: 2 },
|
||||
fc3d: { name: '福彩3D', type: 'welfare', pattern: /福彩\s*3D|3D/i, price: 2 },
|
||||
qlc: { name: '七乐彩', type: 'welfare', pattern: /七\s*乐\s*彩/i, price: 2 },
|
||||
// 体育彩票
|
||||
dlt: { name: '大乐透', type: 'sports', pattern: /大\s*乐\s*透|超级\s*大\s*乐\s*透/i, price: 2 },
|
||||
pl3: { name: '排列3', type: 'sports', pattern: /排列\s*3|排列\s*三/i, price: 2 },
|
||||
pl5: { name: '排列5', type: 'sports', pattern: /排列\s*5|排列\s*五/i, price: 2 },
|
||||
qxc: { name: '七星彩', type: 'sports', pattern: /七\s*星\s*彩/i, price: 2 },
|
||||
};
|
||||
|
||||
// 使用本地tesseract.js-core进行OCR识别
|
||||
async function parseWithLocalTesseract(imagePath) {
|
||||
try {
|
||||
// 使用本地core文件
|
||||
const corePath = path.join(__dirname, '../node_modules/tesseract.js-core');
|
||||
|
||||
const { data } = await Tesseract.recognize(imagePath, 'chi_sim+eng', {
|
||||
corePath: corePath,
|
||||
logger: m => console.log('OCR:', m.status, m.progress)
|
||||
});
|
||||
|
||||
return data.text;
|
||||
} catch (err) {
|
||||
console.error('tesseract.js识别失败:', err.message);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// 解析彩票图片
|
||||
async function parseTicketImage(imagePath) {
|
||||
let text = '';
|
||||
|
||||
try {
|
||||
text = await parseWithLocalTesseract(imagePath);
|
||||
console.log('OCR识别完成, 文本长度:', text.length);
|
||||
} catch (err) {
|
||||
console.error('OCR识别失败:', err);
|
||||
throw new Error('图片识别失败');
|
||||
}
|
||||
|
||||
// 调试:打印识别的文本
|
||||
console.log('识别的文本:', text.substring(0, 500));
|
||||
|
||||
return parseTicketText(text);
|
||||
}
|
||||
|
||||
// 解析彩票文本
|
||||
function parseTicketText(text) {
|
||||
const result = {
|
||||
type: null,
|
||||
game: null,
|
||||
issue: null,
|
||||
numbers: [],
|
||||
bet_count: 1,
|
||||
multiple: 1,
|
||||
is_additional: false,
|
||||
cost: 0,
|
||||
raw_text: text
|
||||
};
|
||||
|
||||
// 识别彩票类型
|
||||
for (const [key, lottery] of Object.entries(LOTTERY_PATTERNS)) {
|
||||
if (lottery.pattern.test(text)) {
|
||||
result.type = lottery.type;
|
||||
result.game = lottery.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 提取期号 - 优先匹配"期号:xxx"格式
|
||||
const issueMatch = text.match(/期\s*号\s*[::]\s*(\d{5,})/);
|
||||
if (issueMatch) {
|
||||
result.issue = issueMatch[1];
|
||||
} else {
|
||||
const issueMatch2 = text.match(/第?\s*(\d{5,})\s*期/);
|
||||
if (issueMatch2) {
|
||||
result.issue = issueMatch2[1];
|
||||
}
|
||||
}
|
||||
|
||||
// 提取注数
|
||||
const betMatch = text.match(/(\d+)\s*注/);
|
||||
if (betMatch) {
|
||||
result.bet_count = parseInt(betMatch[1]);
|
||||
}
|
||||
|
||||
// 提取倍数
|
||||
const multipleMatch = text.match(/(\d+)\s*倍/);
|
||||
if (multipleMatch) {
|
||||
result.multiple = parseInt(multipleMatch[1]);
|
||||
}
|
||||
|
||||
// 检测是否追加
|
||||
result.is_additional = /追加|追加投注/.test(text);
|
||||
|
||||
// 提取金额 - 支持多种格式
|
||||
const costMatch = text.match(/金额\s*[::]\s*(\d+(?:[.,]\d+)?)\s*元|合计[::]\s*(\d+(?:\.\d+)?)\s*元|(\d+(?:\.\d+)?)\s*元/);
|
||||
if (costMatch) {
|
||||
const costStr = (costMatch[1] || costMatch[2] || costMatch[3]).replace(',', '.');
|
||||
result.cost = parseFloat(costStr);
|
||||
}
|
||||
|
||||
// 提取号码 - 根据不同彩票类型
|
||||
result.numbers = extractNumbers(text, result.game);
|
||||
|
||||
// 根据识别到的号码数量更新注数
|
||||
if (result.numbers.length > 0) {
|
||||
result.bet_count = result.numbers.length;
|
||||
}
|
||||
|
||||
// 如果没有识别到金额,根据注数和倍数计算
|
||||
if (!result.cost && result.game && result.numbers.length > 0) {
|
||||
const lottery = Object.values(LOTTERY_PATTERNS).find(l => l.name === result.game);
|
||||
if (lottery) {
|
||||
let basePrice = lottery.price * result.bet_count * result.multiple;
|
||||
if (result.is_additional) basePrice += result.bet_count * result.multiple;
|
||||
result.cost = basePrice;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 提取号码
|
||||
function extractNumbers(text, game) {
|
||||
const numbers = [];
|
||||
|
||||
// 预处理文本:修复常见OCR错误
|
||||
let cleanText = text
|
||||
.replace(/[oO]/g, '0') // o和O经常被误识别为0
|
||||
.replace(/[D]/g, '0') // D经常被误识别
|
||||
.replace(/[lI|]/g, '1') // l和I和|经常被误识别为1
|
||||
.replace(/[S\$§]/g, '5') // S和$和§经常被误识别为5
|
||||
.replace(/[@®»«]/g, '') // 去掉这些特殊字符
|
||||
.replace(/[::]/g, ' ') // 冒号替换为空格
|
||||
.replace(/[g]/g, '9'); // g经常被误识别为9
|
||||
|
||||
// 处理连在一起的数字:将6位以上连续数字按每2位分割
|
||||
cleanText = cleanText.replace(/\b(\d{6,})\b/g, (match) => {
|
||||
return match.match(/.{1,2}/g).join(' ');
|
||||
});
|
||||
// 处理4位连续数字
|
||||
cleanText = cleanText.replace(/\b(\d{4})\b/g, (match) => {
|
||||
return match.slice(0, 2) + ' ' + match.slice(2);
|
||||
});
|
||||
|
||||
// 移除开奖号码行(包含"开奖号码"的行)
|
||||
cleanText = cleanText.split('\n')
|
||||
.filter(line => !line.includes('开奖') && !line.includes('号码'))
|
||||
.join('\n');
|
||||
|
||||
if (game === '双色球') {
|
||||
// 双色球: 6红+1蓝,支持多种格式
|
||||
const patterns = [
|
||||
/(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})[-+](\d{2})/g,
|
||||
/(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s*[+|]\s*(\d{2})/g,
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const matches = cleanText.matchAll(pattern);
|
||||
for (const match of matches) {
|
||||
numbers.push({
|
||||
red: [match[1], match[2], match[3], match[4], match[5], match[6]],
|
||||
blue: match[7]
|
||||
});
|
||||
}
|
||||
if (numbers.length > 0) break;
|
||||
}
|
||||
} else if (game === '大乐透') {
|
||||
// 大乐透: 5前区+2后区
|
||||
const patterns = [
|
||||
// 带空格的标准格式
|
||||
/(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})[-+](\d{2})\s+(\d{2})/g,
|
||||
/(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s*[+|]\s*(\d{2})\s+(\d{2})/g,
|
||||
// 连在一起无空格的格式(第一注可能这样)
|
||||
/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})[-+](\d{2})(\d{2})/g,
|
||||
/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})[+|](\d{2})(\d{2})/g,
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const matches = cleanText.matchAll(pattern);
|
||||
for (const match of matches) {
|
||||
numbers.push({
|
||||
front: [match[1], match[2], match[3], match[4], match[5]],
|
||||
back: [match[6], match[7]]
|
||||
});
|
||||
}
|
||||
if (numbers.length > 0) break;
|
||||
}
|
||||
} else if (game === '福彩3D' || game === '排列3') {
|
||||
// 3位数
|
||||
const matches = cleanText.matchAll(/[^\d](\d)\s*(\d)\s*(\d)[^\d]/g);
|
||||
for (const match of matches) {
|
||||
numbers.push([match[1], match[2], match[3]]);
|
||||
}
|
||||
}
|
||||
|
||||
return numbers;
|
||||
}
|
||||
|
||||
module.exports = { parseTicketImage, parseTicketText };
|
||||
|
After Width: | Height: | Size: 229 KiB |
|
After Width: | Height: | Size: 247 KiB |
|
After Width: | Height: | Size: 235 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 229 KiB |
|
After Width: | Height: | Size: 242 KiB |
|
After Width: | Height: | Size: 272 KiB |
|
After Width: | Height: | Size: 216 KiB |
|
After Width: | Height: | Size: 267 KiB |
|
After Width: | Height: | Size: 284 KiB |
|
After Width: | Height: | Size: 287 KiB |
|
After Width: | Height: | Size: 253 KiB |
|
After Width: | Height: | Size: 285 KiB |
|
After Width: | Height: | Size: 264 KiB |
|
After Width: | Height: | Size: 295 KiB |
|
After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 283 KiB |
|
After Width: | Height: | Size: 278 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 254 KiB |
|
After Width: | Height: | Size: 254 KiB |
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 268 KiB |
|
After Width: | Height: | Size: 267 KiB |
|
After Width: | Height: | Size: 246 KiB |
|
After Width: | Height: | Size: 262 KiB |
|
After Width: | Height: | Size: 261 KiB |
|
After Width: | Height: | Size: 4.0 MiB |
|
After Width: | Height: | Size: 4.0 MiB |
|
After Width: | Height: | Size: 4.0 MiB |
|
After Width: | Height: | Size: 4.0 MiB |
|
After Width: | Height: | Size: 4.0 MiB |
|
After Width: | Height: | Size: 311 KiB |
|
After Width: | Height: | Size: 254 KiB |
|
After Width: | Height: | Size: 324 KiB |
|
After Width: | Height: | Size: 237 KiB |
|
After Width: | Height: | Size: 249 KiB |