Skip to content

Commit

Permalink
add ui
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhangWei-KUMO committed Dec 13, 2024
1 parent e38e44f commit aecd9e4
Show file tree
Hide file tree
Showing 14 changed files with 1,768 additions and 276 deletions.
4 changes: 2 additions & 2 deletions __tests__/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<body>
<div id="qrcode"></div>
<script>
const ws = new WebSocket('ws://124.220.108.218:1982');
const ws = new WebSocket('ws://124.220.108.218:1983');

ws.onopen = () => {
console.log("Connected to WebSocket server");
Expand All @@ -22,7 +22,7 @@
};

ws.onerror = (error) => {
console.error("WebSocket error:", error);
// console.error("WebSocket error:", error);
};
</script>
</body>
Expand Down
33 changes: 17 additions & 16 deletions db/chats.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@ import moment from 'moment-timezone'; // Import moment-timezone for timezones

// Set the default timezone to Beijing
moment.tz.setDefault("Asia/Shanghai");


// 数据库文件名
const dbFile = 'chats.db';

// 创建数据库连接
let db = new sqlite3.Database(dbFile, (err) => {
if (err) {
console.error(err.message);
// console.error(err.message);
} else {
console.log('连接聊天记录数据库');
db.run(`
Expand All @@ -29,37 +26,41 @@ let db = new sqlite3.Database(dbFile, (err) => {

// 日志记录函数
export function chat(name, message) {

// Limit message length to 200 characters
// if(!message) return
// const truncatedMessage = message.substring(0, 200);

const timestamp = moment().format("YYYY-MM-DD HH:mm"); // Format timestamp with Beijing time
db.run(`INSERT INTO chats (timestamp, name, message) VALUES (?, ?, ?)`, [timestamp, name, message], function (err) {
if (err) {
console.error(err.message);
// console.error(err.message);
}
});


// Keep only the latest 200 log entries
db.run(`DELETE FROM chats WHERE id NOT IN (SELECT id FROM logs ORDER BY id DESC LIMIT 200)`);


}



// 查询日志
export function getChats() {
return new Promise((resolve, reject) => {
db.all(`SELECT * FROM chats ORDER BY timestamp DESC`, [], (err, rows) => {
if (err) {
console.error(err.message);
// console.error(err.message);
reject(err);
} else {
resolve(rows);
}
});
});
}

// 删除所有聊天记录
export function deleteChats() {
return new Promise((resolve, reject) => {
db.run(`DELETE FROM chats`, [], function(err) {
if (err) {
// console.error(err.message);
reject(err);
} else {
resolve({message: '所有日志已删除'}); // Resolve with a success message
}
});
});
}
126 changes: 126 additions & 0 deletions db/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import sqlite3 from 'sqlite3';

// 数据库文件名
const dbFile = 'config.db'; // Use a separate DB file for config

// Create the database connection
const db = new sqlite3.Database(dbFile, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('配置文件数据库连接成功');
// Create the config table if it doesn't exist
db.run(`
CREATE TABLE IF NOT EXISTS config (
id INTEGER PRIMARY KEY AUTOINCREMENT,
difyApiKey TEXT,
geminiApiKey TEXT,
greeting TEXT,
pushTime TEXT,
groups TEXT,
isEnable INTEGER,
isPushEnable INTEGER
)
`, (err) => {
if (err) {
console.error("Error creating config table:", err.message);
} else {
// Insert initial config if the table is empty
db.get("SELECT COUNT(*) AS count FROM config", [], (err, row) => {
if (err) {
console.error("Error checking config table:", err.message);
} else if (row.count === 0) {
const defaultConfig = {
difyApiKey: '',
geminiApiKey: '',
greeting: 'Hello!',
pushTime: '09:00', // Example default time
groups: '[]', // Example default groups
isEnable: 1, // 1 for true, 0 for false
isPushEnable: 1, // 1 for true, 0 for false

};
insertConfig(defaultConfig) // Use the insertConfig function
.then(() => console.log("写入默认配置"))
.catch(err => console.error("写入数据错误:", err));
}
});
}
});

}
});



// Function to insert or update config (upsert)
export function saveConfig(config) {
return new Promise((resolve, reject) => {
db.get("SELECT COUNT(*) AS count FROM config", [], (err, row) => {
if (err) {
reject(err);
} else if (row.count === 0) {
// Insert if no config exists
insertConfig(config).then(resolve).catch(reject);
} else {
// Update if config already exists (assuming only one config row)
updateConfig(config).then(resolve).catch(reject);
}
});
});
}



// Helper function to insert config
function insertConfig(config) {
const { difyApiKey, geminiApiKey,greeting, groups, pushTime, isEnable,isPushEnable } = config;
return new Promise((resolve, reject) => {
db.run(`INSERT INTO config (difyApiKey,geminiApiKey, greeting, groups,pushTime, isEnable, isPushEnable) VALUES (?, ?, ?, ?, ?, ?, ?)`,
[difyApiKey, geminiApiKey,greeting, groups,pushTime, isEnable ? 1 : 0, isPushEnable ? 1 : 0],
function (err) {
if (err) {
reject(err);
} else {
resolve(this.lastID);
}
});
});
}

// Helper function to update config
function updateConfig(config) {
const { difyApiKey, geminiApiKey,greeting, groups, pushTime, isEnable,isPushEnable } = config;
return new Promise((resolve, reject) => {
db.run(`UPDATE config SET difyApiKey = ?,geminiApiKey= ?, greeting = ?, groups = ?, pushTime = ?, isEnable = ? ,isPushEnable = ? WHERE id = 1`, // 更新第一列
[difyApiKey, geminiApiKey,greeting, groups, pushTime, isEnable ? 1 : 0,isPushEnable ? 1 : 0],
function (err) {
if (err) {
reject(err);
} else {
resolve(this.changes);
}
});
});
}



// Get config
export function getConfig() {
return new Promise((resolve, reject) => {
db.get(`SELECT * FROM config WHERE id = 1`, [], (err, row) => { // Select the first row
if (err) {
reject(err);
} else if (!row) {
resolve(null); // No config found.
} else {

// Convert isEnable back to boolean
row.isEnable = !!row.isEnable;
row.isPushEnable = !!row.isPushEnable;
resolve(row);
}
});
});
}
74 changes: 39 additions & 35 deletions db/logs.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,70 @@
import sqlite3 from 'sqlite3';
import moment from 'moment-timezone'; // Import moment-timezone for timezones
import moment from 'moment-timezone';

// Set the default timezone to Beijing
moment.tz.setDefault("Asia/Shanghai");


// 数据库文件名
const dbFile = 'logs.db';

// 创建数据库连接
let db = new sqlite3.Database(dbFile, (err) => {
const db = new sqlite3.Database(dbFile, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
if (err) {
console.error(err.message);
console.error('Error opening database:', err.message);
} else {
console.log('连接日志数据库');
// 创建日志表(如果不存在)
console.log('连接日志数据库成功');
// Create the logs table
db.run(`
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), -- Use STRFTIME for timestamps
level TEXT,
message TEXT
)
`);
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT, -- Store timestamp as TEXT for simplicity
level TEXT,
message TEXT
)
`, (err) => { // Handle table creation errors
if (err) {
console.error("Error creating logs table:", err.message);
}
});
}
});



// 日志记录函数
// 记录日志
export function log(level, message) {

// Limit message length to 200 characters
// if(!message) return
// const truncatedMessage = message.substring(0, 200);

const timestamp = moment().format("YYYY-MM-DD HH:mm"); // Format timestamp with Beijing time
db.run(`INSERT INTO logs (timestamp, level, message) VALUES (?, ?, ?)`, [timestamp, level, message], function (err) {
if (err) {
console.error(err.message);
}
const timestamp = moment().format("YYYY-MM-DD HH:mm:ss"); // Add seconds
db.serialize(() => { // Ensure operations are executed in order
db.run(`INSERT INTO logs (timestamp, level, message) VALUES (?, ?, ?)`, [timestamp, level, message], (err) => {
if (err) {
console.error('Error inserting log:', err.message); // Log insertion errors
}
});
});


// Keep only the latest 200 log entries
db.run(`DELETE FROM logs WHERE id NOT IN (SELECT id FROM logs ORDER BY id DESC LIMIT 200)`);


}



// 查询日志
export function getLogs() {
return new Promise((resolve, reject) => {
db.all(`SELECT * FROM logs ORDER BY timestamp DESC`, [], (err, rows) => { // Order by timestamp descending
if (err) {
console.error("触发错误");
console.error(err.message);
reject(err);
} else {
resolve(rows);
}
});
});
}

// 删除所有日志
export function deleteLogs() {
return new Promise((resolve, reject) => {
db.run(`DELETE FROM logs`, [], function(err) {
if (err) {
console.error(err.message);
reject(err);
} else {
resolve({message: '所有日志已删除'}); // Resolve with a success message
}
});
});
}
Loading

0 comments on commit aecd9e4

Please sign in to comment.