mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-06-02 00:57:41 +08:00
feat: web channel optimization
This commit is contained in:
@@ -3,163 +3,849 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Chat</title>
|
<title>AI Assistant</title>
|
||||||
|
<link rel="icon" href="assets/favicon.ico" type="image/x-icon">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/python.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/java.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/go.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/cpp.min.js"></script>
|
||||||
<style>
|
<style>
|
||||||
body {
|
:root {
|
||||||
font-family: Arial, sans-serif;
|
--primary-color: #10a37f;
|
||||||
display: flex;
|
--primary-hover: #0d8a6c;
|
||||||
flex-direction: column;
|
--bg-color: #f7f7f8;
|
||||||
height: 100vh; /* 占据所有高度 */
|
--chat-bg: #ffffff;
|
||||||
|
--user-msg-bg: #10a37f;
|
||||||
|
--bot-msg-bg: #f7f7f8;
|
||||||
|
--border-color: #e5e5e5;
|
||||||
|
--text-color: #343541;
|
||||||
|
--text-light: #6e6e80;
|
||||||
|
--shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
/* background-color: #f8f9fa; */
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
#chat-container {
|
|
||||||
|
body {
|
||||||
|
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||||
|
color: var(--text-color);
|
||||||
|
background-color: var(--bg-color);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
height: 100vh;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
#app-container {
|
||||||
|
display: flex;
|
||||||
|
height: 100vh;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 500px;
|
|
||||||
margin: auto;
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
border-radius: 5px;
|
|
||||||
overflow: hidden;
|
|
||||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
|
||||||
flex: 1; /* 使聊天容器占据剩余空间 */
|
|
||||||
}
|
}
|
||||||
#messages {
|
|
||||||
|
#sidebar {
|
||||||
|
width: 260px;
|
||||||
|
background-color: #202123;
|
||||||
|
color: white;
|
||||||
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
display: flex;
|
transition: all 0.3s ease;
|
||||||
flex: 1;
|
|
||||||
overflow-y: auto;
|
|
||||||
padding: 10px;
|
|
||||||
overflow-y: auto;
|
|
||||||
border-bottom: 1px solid #ccc;
|
|
||||||
background-color: #ffffff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.message {
|
|
||||||
margin: 5px 0; /* 间隔 */
|
|
||||||
padding: 10px 15px; /* 内边距 */
|
|
||||||
border-radius: 15px; /* 圆角 */
|
|
||||||
max-width: 80%; /* 限制最大宽度 */
|
|
||||||
min-width: 80px; /* 设置最小宽度 */
|
|
||||||
min-height: 40px; /* 设置最小高度 */
|
|
||||||
word-wrap: break-word; /* 自动换行 */
|
|
||||||
position: relative; /* 时间戳定位 */
|
|
||||||
display: inline-block; /* 内容自适应宽度 */
|
|
||||||
box-sizing: border-box; /* 包括内边距和边框 */
|
|
||||||
flex-shrink: 0; /* 禁止高度被压缩 */
|
|
||||||
word-wrap: break-word; /* 自动换行,防止单行过长 */
|
|
||||||
white-space: normal; /* 允许正常换行 */
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bot {
|
#new-chat {
|
||||||
background-color: #f1f1f1; /* 灰色背景 */
|
margin: 15px;
|
||||||
color: black; /* 黑色字体 */
|
padding: 12px;
|
||||||
align-self: flex-start; /* 左对齐 */
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
margin-right: auto; /* 确保消息靠左 */
|
border-radius: 6px;
|
||||||
text-align: left; /* 内容左对齐 */
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
}
|
}
|
||||||
|
|
||||||
.user {
|
#new-chat:hover {
|
||||||
background-color: #2bc840; /* 蓝色背景 */
|
background-color: rgba(255, 255, 255, 0.1);
|
||||||
align-self: flex-end; /* 右对齐 */
|
|
||||||
margin-left: auto; /* 确保消息靠右 */
|
|
||||||
text-align: left; /* 内容左对齐 */
|
|
||||||
}
|
}
|
||||||
.timestamp {
|
|
||||||
font-size: 0.8em; /* 时间戳字体大小 */
|
#new-chat i {
|
||||||
color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
|
|
||||||
margin-bottom: 5px; /* 时间戳下方间距 */
|
|
||||||
display: block; /* 时间戳独占一行 */
|
|
||||||
}
|
|
||||||
#input-container {
|
|
||||||
display: flex;
|
|
||||||
padding: 10px;
|
|
||||||
background-color: #ffffff;
|
|
||||||
border-top: 1px solid #ccc;
|
|
||||||
}
|
|
||||||
#input {
|
|
||||||
flex: 1;
|
|
||||||
padding: 10px;
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
border-radius: 5px;
|
|
||||||
margin-right: 10px;
|
margin-right: 10px;
|
||||||
}
|
}
|
||||||
#send {
|
|
||||||
padding: 10px;
|
#chat-history {
|
||||||
border: none;
|
flex: 1;
|
||||||
background-color: #007bff;
|
overflow-y: auto;
|
||||||
color: white;
|
padding: 10px 15px;
|
||||||
border-radius: 5px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.history-item {
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-item:hover {
|
||||||
|
background-color: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-item i {
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar-footer {
|
||||||
|
padding: 15px;
|
||||||
|
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#user-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 5px;
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#user-info:hover {
|
||||||
|
background-color: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#user-avatar {
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
background-color: #10a37f;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#main-content {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-header {
|
||||||
|
padding: 15px 20px;
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
background-color: var(--chat-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
#menu-toggle {
|
||||||
|
display: none;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
font-size: 20px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text-color);
|
||||||
|
margin-right: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#header-logo {
|
||||||
|
height: 30px;
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-title {
|
||||||
|
font-weight: 600;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 20px;
|
||||||
|
background-color: var(--chat-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-container {
|
||||||
|
display: flex;
|
||||||
|
padding: 15px 20px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bot-container {
|
||||||
|
background-color: var(--bot-msg-bg);
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
width: 100%;
|
||||||
|
margin: 0 -20px;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar {
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
border-radius: 2px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
margin-right: 15px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bot-avatar {
|
||||||
|
background-color: #10a37f;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-avatar {
|
||||||
|
background-color: #d9d9e3;
|
||||||
|
color: #40414f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
flex: 1;
|
||||||
|
line-height: 1.6;
|
||||||
|
padding-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
width: 100%;
|
||||||
|
word-wrap: break-word;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message pre {
|
||||||
|
background-color: #f0f0f0;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message code {
|
||||||
|
font-family: monospace;
|
||||||
|
background-color: rgba(0, 0, 0, 0.05);
|
||||||
|
padding: 2px 4px;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message pre code {
|
||||||
|
background-color: transparent;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message blockquote {
|
||||||
|
border-left: 4px solid #ddd;
|
||||||
|
padding-left: 10px;
|
||||||
|
color: #777;
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message th, .message td {
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
padding: 8px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message th {
|
||||||
|
background-color: #f2f2f2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timestamp {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--text-light);
|
||||||
|
margin-top: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#input-container {
|
||||||
|
padding: 15px 20px;
|
||||||
|
background-color: var(--chat-bg);
|
||||||
|
border-top: 1px solid var(--border-color);
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#input-wrapper {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 768px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
#input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px 45px 12px 15px;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--text-color);
|
||||||
|
background-color: var(--chat-bg);
|
||||||
|
resize: none;
|
||||||
|
height: 52px;
|
||||||
|
max-height: 200px;
|
||||||
|
overflow-y: auto;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
transition: border-color 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
#send {
|
||||||
|
position: absolute;
|
||||||
|
right: 10px;
|
||||||
|
bottom: 10px;
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
color: var(--primary-color);
|
||||||
|
font-size: 20px;
|
||||||
|
cursor: pointer;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border-radius: 4px;
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
#send:hover {
|
#send:hover {
|
||||||
background-color: #0056b3;
|
background-color: rgba(16, 163, 127, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#send:disabled {
|
||||||
|
color: var(--border-color);
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
#welcome-screen {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100%;
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#welcome-title {
|
||||||
|
font-size: 2rem;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
#welcome-subtitle {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
color: var(--text-light);
|
||||||
|
margin-bottom: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.examples-container {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||||
|
gap: 15px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 900px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.example-card {
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 15px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.example-card:hover {
|
||||||
|
background-color: #f0f0f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.example-title {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.example-text {
|
||||||
|
color: var(--text-light);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Responsive styles */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
#sidebar {
|
||||||
|
position: fixed;
|
||||||
|
left: -260px;
|
||||||
|
height: 100%;
|
||||||
|
z-index: 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.active {
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#menu-toggle {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-container {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bot-container {
|
||||||
|
padding: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#input-container {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.examples-container {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
#header-logo {
|
||||||
|
height: 24px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark mode support */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--bg-color: #343541;
|
||||||
|
--chat-bg: #444654;
|
||||||
|
--bot-msg-bg: #444654;
|
||||||
|
--border-color: #565869;
|
||||||
|
--text-color: #ececf1;
|
||||||
|
--text-light: #acacbe;
|
||||||
|
}
|
||||||
|
|
||||||
|
#input {
|
||||||
|
background-color: #40414f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.example-card {
|
||||||
|
background-color: #40414f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.example-card:hover {
|
||||||
|
background-color: #565869;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message pre {
|
||||||
|
background-color: #2d2d2d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message code {
|
||||||
|
background-color: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message blockquote {
|
||||||
|
border-left-color: #555;
|
||||||
|
color: #aaa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message th, .message td {
|
||||||
|
border-color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message th {
|
||||||
|
background-color: #3a3a3a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs {
|
||||||
|
background: #2d2d2d !important;
|
||||||
|
color: #d4d4d4 !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="chat-container">
|
<div id="app-container">
|
||||||
<div id="messages"></div>
|
<div id="sidebar">
|
||||||
<div id="input-container">
|
<div id="new-chat">
|
||||||
<input type="text" id="input" placeholder="输入消息..." />
|
<i class="fas fa-plus"></i>
|
||||||
<button id="send">发送</button>
|
<span>新对话</span>
|
||||||
|
</div>
|
||||||
|
<div id="chat-history">
|
||||||
|
<!-- 历史对话将在这里动态添加 -->
|
||||||
|
</div>
|
||||||
|
<div id="sidebar-footer">
|
||||||
|
<div id="user-info">
|
||||||
|
<div id="user-avatar">U</div>
|
||||||
|
<span>用户</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content">
|
||||||
|
<div id="chat-header">
|
||||||
|
<button id="menu-toggle">
|
||||||
|
<i class="fas fa-bars"></i>
|
||||||
|
</button>
|
||||||
|
<img id="header-logo" src="assets/logo.jpg" alt="AI Assistant Logo">
|
||||||
|
<div id="chat-title">AI 助手</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="messages">
|
||||||
|
<!-- 初始欢迎界面 -->
|
||||||
|
<div id="welcome-screen">
|
||||||
|
<h1 id="welcome-title">AI 助手</h1>
|
||||||
|
<p id="welcome-subtitle">我可以回答问题、提供信息或者帮助您完成各种任务</p>
|
||||||
|
|
||||||
|
<div class="examples-container">
|
||||||
|
<div class="example-card">
|
||||||
|
<div class="example-title">解释复杂概念</div>
|
||||||
|
<div class="example-text">用简单的语言解释量子计算</div>
|
||||||
|
</div>
|
||||||
|
<div class="example-card">
|
||||||
|
<div class="example-title">创意写作</div>
|
||||||
|
<div class="example-text">写一个关于未来城市的短篇故事</div>
|
||||||
|
</div>
|
||||||
|
<div class="example-card">
|
||||||
|
<div class="example-title">编程帮助</div>
|
||||||
|
<div class="example-text">如何用Python创建一个简单的网络爬虫?</div>
|
||||||
|
</div>
|
||||||
|
<div class="example-card">
|
||||||
|
<div class="example-title">生活建议</div>
|
||||||
|
<div class="example-text">推荐一些提高工作效率的方法</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 消息将在这里动态添加 -->
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="input-container">
|
||||||
|
<div id="input-wrapper">
|
||||||
|
<textarea id="input" placeholder="发送消息..." rows="1"></textarea>
|
||||||
|
<button id="send" disabled>
|
||||||
|
<i class="fas fa-paper-plane"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
// DOM 元素
|
||||||
const messagesDiv = document.getElementById('messages');
|
const messagesDiv = document.getElementById('messages');
|
||||||
const input = document.getElementById('input');
|
const input = document.getElementById('input');
|
||||||
const sendButton = document.getElementById('send');
|
const sendButton = document.getElementById('send');
|
||||||
|
const menuToggle = document.getElementById('menu-toggle');
|
||||||
|
const sidebar = document.getElementById('sidebar');
|
||||||
|
const welcomeScreen = document.getElementById('welcome-screen');
|
||||||
|
const exampleCards = document.querySelectorAll('.example-card');
|
||||||
|
const newChatButton = document.getElementById('new-chat');
|
||||||
|
const chatHistory = document.getElementById('chat-history');
|
||||||
|
|
||||||
// 生成唯一的 user_id
|
// 在页面顶部添加这些变量和函数
|
||||||
const userId = 'user_' + Math.random().toString(36).substr(2, 9);
|
let userId = 'user_' + Math.random().toString(36).substring(2, 10);
|
||||||
|
let currentSessionId = 'session_' + Date.now();
|
||||||
|
|
||||||
|
// 轮询获取消息
|
||||||
|
function pollMessages() {
|
||||||
|
fetch(`/poll/${userId}`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(messages => {
|
||||||
|
if (messages && messages.length > 0) {
|
||||||
|
console.log('Received messages via polling:', messages);
|
||||||
|
|
||||||
|
// 隐藏欢迎屏幕
|
||||||
|
document.getElementById('welcome-screen').style.display = 'none';
|
||||||
|
|
||||||
|
// 处理每条消息
|
||||||
|
messages.forEach(message => {
|
||||||
|
addBotMessage(message.content, new Date(message.timestamp * 1000));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 继续轮询
|
||||||
|
setTimeout(pollMessages, 1000);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Polling error:', error);
|
||||||
|
setTimeout(pollMessages, 3000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动轮询
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
pollMessages();
|
||||||
|
});
|
||||||
|
|
||||||
// 连接 SSE
|
// 自动调整文本区域高度
|
||||||
const eventSource = new EventSource(`/sse/${userId}`);
|
input.addEventListener('input', function() {
|
||||||
|
this.style.height = 'auto';
|
||||||
|
this.style.height = (this.scrollHeight) + 'px';
|
||||||
|
|
||||||
|
// 启用/禁用发送按钮
|
||||||
|
sendButton.disabled = !this.value.trim();
|
||||||
|
});
|
||||||
|
|
||||||
eventSource.onmessage = function(event) {
|
// 处理示例卡片点击
|
||||||
const message = JSON.parse(event.data);
|
exampleCards.forEach(card => {
|
||||||
const messageDiv = document.createElement('div');
|
card.addEventListener('click', function() {
|
||||||
messageDiv.className = 'message bot';
|
const exampleText = this.querySelector('.example-text').textContent;
|
||||||
const timestamp = new Date(message.timestamp).toLocaleTimeString(); // 假设消息中有时间戳
|
input.value = exampleText;
|
||||||
messageDiv.innerHTML = `<div class="timestamp">${timestamp}</div>${message.content}`; // 显示时间
|
input.dispatchEvent(new Event('input'));
|
||||||
messagesDiv.appendChild(messageDiv);
|
input.focus();
|
||||||
messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
|
});
|
||||||
};
|
});
|
||||||
|
|
||||||
|
// 处理菜单切换
|
||||||
|
menuToggle.addEventListener('click', function() {
|
||||||
|
sidebar.classList.toggle('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 处理新对话按钮
|
||||||
|
newChatButton.addEventListener('click', function() {
|
||||||
|
// 清空消息区域
|
||||||
|
while (messagesDiv.firstChild) {
|
||||||
|
if (messagesDiv.firstChild.id === 'welcome-screen') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
messagesDiv.removeChild(messagesDiv.firstChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示欢迎屏幕
|
||||||
|
welcomeScreen.style.display = 'flex';
|
||||||
|
|
||||||
|
// 创建新会话
|
||||||
|
currentSessionId = 'session_' + Date.now();
|
||||||
|
|
||||||
|
// 在移动设备上关闭侧边栏
|
||||||
|
if (window.innerWidth <= 768) {
|
||||||
|
sidebar.classList.remove('active');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加到历史记录
|
||||||
|
addToHistory('新对话', currentSessionId);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 添加到历史记录
|
||||||
|
function addToHistory(title, sessionId) {
|
||||||
|
const historyItem = document.createElement('div');
|
||||||
|
historyItem.className = 'history-item';
|
||||||
|
historyItem.dataset.sessionId = sessionId;
|
||||||
|
historyItem.innerHTML = `
|
||||||
|
<i class="far fa-comment"></i>
|
||||||
|
<span>${title}</span>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 点击加载对话
|
||||||
|
historyItem.addEventListener('click', function() {
|
||||||
|
// 这里可以实现加载历史对话的功能
|
||||||
|
// 在实际应用中,您需要存储和检索历史消息
|
||||||
|
|
||||||
|
// 在移动设备上关闭侧边栏
|
||||||
|
if (window.innerWidth <= 768) {
|
||||||
|
sidebar.classList.remove('active');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 添加到历史记录顶部
|
||||||
|
if (chatHistory.firstChild) {
|
||||||
|
chatHistory.insertBefore(historyItem, chatHistory.firstChild);
|
||||||
|
} else {
|
||||||
|
chatHistory.appendChild(historyItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送按钮点击事件
|
||||||
sendButton.onclick = function() {
|
sendButton.onclick = function() {
|
||||||
sendMessage();
|
sendMessage();
|
||||||
};
|
};
|
||||||
|
|
||||||
input.addEventListener('keypress', function(event) {
|
// 输入框按键事件
|
||||||
if (event.key === 'Enter') {
|
input.addEventListener('keydown', function(event) {
|
||||||
|
// Ctrl+Enter 或 Shift+Enter 添加换行
|
||||||
|
if ((event.ctrlKey || event.shiftKey) && event.key === 'Enter') {
|
||||||
|
const start = this.selectionStart;
|
||||||
|
const end = this.selectionEnd;
|
||||||
|
const value = this.value;
|
||||||
|
|
||||||
|
this.value = value.substring(0, start) + '\n' + value.substring(end);
|
||||||
|
this.selectionStart = this.selectionEnd = start + 1;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
// Enter 键发送消息
|
||||||
|
else if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey) {
|
||||||
sendMessage();
|
sendMessage();
|
||||||
event.preventDefault(); // 防止换行
|
event.preventDefault();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 发送消息函数
|
||||||
function sendMessage() {
|
function sendMessage() {
|
||||||
const userMessage = input.value;
|
const userMessage = input.value.trim();
|
||||||
if (userMessage) {
|
if (userMessage) {
|
||||||
const timestamp = new Date().toISOString(); // 获取当前时间戳
|
// 隐藏欢迎屏幕
|
||||||
|
welcomeScreen.style.display = 'none';
|
||||||
|
|
||||||
|
const timestamp = new Date();
|
||||||
|
|
||||||
|
// 添加用户消息到界面
|
||||||
|
addUserMessage(userMessage, timestamp);
|
||||||
|
|
||||||
|
// 发送到服务器
|
||||||
fetch('/message', {
|
fetch('/message', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ user_id: userId, message: userMessage, timestamp: timestamp }) // 发送时间戳
|
body: JSON.stringify({
|
||||||
|
user_id: userId,
|
||||||
|
message: userMessage,
|
||||||
|
timestamp: timestamp.toISOString(),
|
||||||
|
session_id: currentSessionId
|
||||||
|
})
|
||||||
|
}).then(response => {
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error('Failed to send message');
|
||||||
|
}
|
||||||
|
}).catch(error => {
|
||||||
|
console.error('Error sending message:', error);
|
||||||
});
|
});
|
||||||
const messageDiv = document.createElement('div');
|
|
||||||
messageDiv.className = 'message user';
|
// 清空输入框并重置高度
|
||||||
const userTimestamp = new Date().toLocaleTimeString(); // 获取当前时间
|
input.value = '';
|
||||||
messageDiv.innerHTML = `<div class="timestamp">${userTimestamp}</div>${userMessage}`; // 显示时间
|
input.style.height = '52px';
|
||||||
messagesDiv.appendChild(messageDiv);
|
sendButton.disabled = true;
|
||||||
messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
|
|
||||||
input.value = ''; // 清空输入框
|
// 如果这是第一条消息,添加到历史记录
|
||||||
|
const firstMessageInSession = !messagesDiv.querySelector('.message-container');
|
||||||
|
if (firstMessageInSession) {
|
||||||
|
// 使用消息的前20个字符作为标题
|
||||||
|
const title = userMessage.length > 20 ?
|
||||||
|
userMessage.substring(0, 20) + '...' :
|
||||||
|
userMessage;
|
||||||
|
addToHistory(title, currentSessionId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 格式化消息内容(处理Markdown和代码高亮)
|
||||||
|
function formatMessage(content) {
|
||||||
|
// 配置 marked 以使用 highlight.js
|
||||||
|
marked.setOptions({
|
||||||
|
highlight: function(code, lang) {
|
||||||
|
if (lang && hljs.getLanguage(lang)) {
|
||||||
|
return hljs.highlight(code, { language: lang }).value;
|
||||||
|
}
|
||||||
|
return hljs.highlightAuto(code).value;
|
||||||
|
},
|
||||||
|
breaks: true, // 启用换行符转换为 <br>
|
||||||
|
gfm: true // 启用 GitHub 风格的 Markdown
|
||||||
|
});
|
||||||
|
|
||||||
|
// 使用 marked 解析 Markdown
|
||||||
|
return marked.parse(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加消息后应用代码高亮
|
||||||
|
function applyHighlighting() {
|
||||||
|
document.querySelectorAll('pre code').forEach((block) => {
|
||||||
|
hljs.highlightBlock(block);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新添加消息的函数
|
||||||
|
function addUserMessage(content, timestamp) {
|
||||||
|
const messageContainer = document.createElement('div');
|
||||||
|
messageContainer.className = 'message-container';
|
||||||
|
|
||||||
|
messageContainer.innerHTML = `
|
||||||
|
<div class="avatar user-avatar">
|
||||||
|
<i class="fas fa-user"></i>
|
||||||
|
</div>
|
||||||
|
<div class="message-content">
|
||||||
|
<div class="message">${formatMessage(content)}</div>
|
||||||
|
<div class="timestamp">${formatTimestamp(timestamp)}</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
messagesDiv.appendChild(messageContainer);
|
||||||
|
applyHighlighting(); // 应用代码高亮
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加机器人消息
|
||||||
|
function addBotMessage(content, timestamp) {
|
||||||
|
console.log('Adding bot message:', content, timestamp);
|
||||||
|
|
||||||
|
const botContainer = document.createElement('div');
|
||||||
|
botContainer.className = 'bot-container';
|
||||||
|
|
||||||
|
const messageContainer = document.createElement('div');
|
||||||
|
messageContainer.className = 'message-container';
|
||||||
|
|
||||||
|
// 确保时间戳是有效的 Date 对象
|
||||||
|
if (!(timestamp instanceof Date) || isNaN(timestamp)) {
|
||||||
|
timestamp = new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
messageContainer.innerHTML = `
|
||||||
|
<div class="avatar bot-avatar">
|
||||||
|
<i class="fas fa-robot"></i>
|
||||||
|
</div>
|
||||||
|
<div class="message-content">
|
||||||
|
<div class="message">${formatMessage(content)}</div>
|
||||||
|
<div class="timestamp">${formatTimestamp(timestamp)}</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
botContainer.appendChild(messageContainer);
|
||||||
|
messagesDiv.appendChild(botContainer);
|
||||||
|
applyHighlighting(); // 应用代码高亮
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 格式化时间戳
|
||||||
|
function formatTimestamp(date) {
|
||||||
|
return date.toLocaleTimeString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 滚动到底部
|
||||||
|
function scrollToBottom() {
|
||||||
|
messagesDiv.scrollTop = messagesDiv.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理窗口大小变化
|
||||||
|
window.addEventListener('resize', function() {
|
||||||
|
if (window.innerWidth > 768) {
|
||||||
|
sidebar.classList.remove('active');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 初始化
|
||||||
|
input.focus();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
BIN
channel/web/static/favicon.ico
Normal file
BIN
channel/web/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
BIN
channel/web/static/logo.jpg
Normal file
BIN
channel/web/static/logo.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -11,6 +11,7 @@ from common.log import logger
|
|||||||
from common.singleton import singleton
|
from common.singleton import singleton
|
||||||
from config import conf
|
from config import conf
|
||||||
import os
|
import os
|
||||||
|
import mimetypes # 添加这行来处理MIME类型
|
||||||
|
|
||||||
|
|
||||||
class WebMessage(ChatMessage):
|
class WebMessage(ChatMessage):
|
||||||
@@ -53,6 +54,10 @@ class WebChannel(ChatChannel):
|
|||||||
|
|
||||||
def send(self, reply: Reply, context: Context):
|
def send(self, reply: Reply, context: Context):
|
||||||
try:
|
try:
|
||||||
|
if reply.type in self.NOT_SUPPORT_REPLYTYPE:
|
||||||
|
logger.warning(f"Web channel doesn't support {reply.type} yet")
|
||||||
|
return
|
||||||
|
|
||||||
if reply.type == ReplyType.IMAGE:
|
if reply.type == ReplyType.IMAGE:
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
@@ -79,25 +84,28 @@ class WebChannel(ChatChannel):
|
|||||||
else:
|
else:
|
||||||
print(reply.content)
|
print(reply.content)
|
||||||
|
|
||||||
# 获取用户ID,如果没有则使用默认值
|
# 获取用户ID
|
||||||
# user_id = getattr(context.get("session", None), "session_id", "default_user")
|
user_id = context.get("receiver", None)
|
||||||
user_id = context["receiver"]
|
if not user_id:
|
||||||
|
logger.error("No receiver found in context, cannot send message")
|
||||||
|
return
|
||||||
|
|
||||||
# 确保用户有对应的消息队列
|
# 确保用户有对应的消息队列
|
||||||
if user_id not in self.message_queues:
|
if user_id not in self.message_queues:
|
||||||
self.message_queues[user_id] = Queue()
|
self.message_queues[user_id] = Queue()
|
||||||
|
logger.debug(f"Created message queue for user {user_id}")
|
||||||
|
|
||||||
# 将消息放入对应用户的队列
|
# 将消息放入对应用户的队列
|
||||||
message_data = {
|
message_data = {
|
||||||
"type": str(reply.type),
|
"type": str(reply.type),
|
||||||
"content": reply.content,
|
"content": reply.content,
|
||||||
"timestamp": time.time()
|
"timestamp": time.time() # 使用 Unix 时间戳
|
||||||
}
|
}
|
||||||
self.message_queues[user_id].put(message_data)
|
self.message_queues[user_id].put(message_data)
|
||||||
logger.debug(f"Message queued for user {user_id}")
|
logger.debug(f"Message queued for user {user_id}: {reply.content[:30]}...")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error in send method: {e}")
|
logger.error(f"Error in send method: {e}")
|
||||||
raise
|
|
||||||
|
|
||||||
def sse_handler(self, user_id):
|
def sse_handler(self, user_id):
|
||||||
"""
|
"""
|
||||||
@@ -107,9 +115,12 @@ class WebChannel(ChatChannel):
|
|||||||
web.header('Cache-Control', 'no-cache')
|
web.header('Cache-Control', 'no-cache')
|
||||||
web.header('Connection', 'keep-alive')
|
web.header('Connection', 'keep-alive')
|
||||||
|
|
||||||
|
logger.debug(f"SSE connection established for user {user_id}")
|
||||||
|
|
||||||
# 确保用户有消息队列
|
# 确保用户有消息队列
|
||||||
if user_id not in self.message_queues:
|
if user_id not in self.message_queues:
|
||||||
self.message_queues[user_id] = Queue()
|
self.message_queues[user_id] = Queue()
|
||||||
|
logger.debug(f"Created new message queue for user {user_id}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
@@ -118,19 +129,19 @@ class WebChannel(ChatChannel):
|
|||||||
yield f": heartbeat\n\n"
|
yield f": heartbeat\n\n"
|
||||||
|
|
||||||
# 非阻塞方式获取消息
|
# 非阻塞方式获取消息
|
||||||
if not self.message_queues[user_id].empty():
|
if user_id in self.message_queues and not self.message_queues[user_id].empty():
|
||||||
message = self.message_queues[user_id].get_nowait()
|
message = self.message_queues[user_id].get_nowait()
|
||||||
yield f"data: {json.dumps(message)}\n\n"
|
logger.debug(f"Sending message to user {user_id}: {message}")
|
||||||
|
data = json.dumps(message)
|
||||||
|
yield f"data: {data}\n\n"
|
||||||
|
logger.debug(f"Message sent to user {user_id}")
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"SSE Error: {e}")
|
logger.error(f"SSE Error for user {user_id}: {str(e)}")
|
||||||
break
|
break
|
||||||
finally:
|
finally:
|
||||||
# 清理资源
|
# 清理资源
|
||||||
if user_id in self.message_queues:
|
logger.debug(f"SSE connection closed for user {user_id}")
|
||||||
# 只有当队列为空时才删除
|
|
||||||
if self.message_queues[user_id].empty():
|
|
||||||
del self.message_queues[user_id]
|
|
||||||
|
|
||||||
def post_message(self):
|
def post_message(self):
|
||||||
"""
|
"""
|
||||||
@@ -141,6 +152,7 @@ class WebChannel(ChatChannel):
|
|||||||
json_data = json.loads(data)
|
json_data = json.loads(data)
|
||||||
user_id = json_data.get('user_id', 'default_user')
|
user_id = json_data.get('user_id', 'default_user')
|
||||||
prompt = json_data.get('message', '')
|
prompt = json_data.get('message', '')
|
||||||
|
session_id = json_data.get('session_id', f'session_{int(time.time())}')
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
return json.dumps({"status": "error", "message": "Invalid JSON"})
|
return json.dumps({"status": "error", "message": "Invalid JSON"})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -151,16 +163,22 @@ class WebChannel(ChatChannel):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
msg_id = self._generate_msg_id()
|
msg_id = self._generate_msg_id()
|
||||||
context = self._compose_context(ContextType.TEXT, prompt, msg=WebMessage(msg_id,
|
web_message = WebMessage(
|
||||||
prompt,
|
msg_id=msg_id,
|
||||||
from_user_id=user_id,
|
content=prompt,
|
||||||
other_user_id = user_id
|
from_user_id=user_id,
|
||||||
))
|
to_user_id="Chatgpt", # 明确指定接收者
|
||||||
|
other_user_id=user_id
|
||||||
|
)
|
||||||
|
|
||||||
|
context = self._compose_context(ContextType.TEXT, prompt, msg=web_message)
|
||||||
if not context:
|
if not context:
|
||||||
return json.dumps({"status": "error", "message": "Failed to process message"})
|
return json.dumps({"status": "error", "message": "Failed to process message"})
|
||||||
|
|
||||||
|
# 确保上下文包含必要的信息
|
||||||
context["isgroup"] = False
|
context["isgroup"] = False
|
||||||
# context["session"] = web.storage(session_id=user_id)
|
context["receiver"] = user_id # 添加接收者信息,用于send方法中识别用户
|
||||||
|
context["session_id"] = session_id # 添加会话ID
|
||||||
|
|
||||||
self.produce(context)
|
self.produce(context)
|
||||||
return json.dumps({"status": "success", "message": "Message received"})
|
return json.dumps({"status": "success", "message": "Message received"})
|
||||||
@@ -178,15 +196,33 @@ class WebChannel(ChatChannel):
|
|||||||
def startup(self):
|
def startup(self):
|
||||||
print("\nWeb Channel is running, please visit http://localhost:9899/chat")
|
print("\nWeb Channel is running, please visit http://localhost:9899/chat")
|
||||||
|
|
||||||
|
# 确保静态文件目录存在
|
||||||
|
static_dir = os.path.join(os.path.dirname(__file__), 'static')
|
||||||
|
if not os.path.exists(static_dir):
|
||||||
|
os.makedirs(static_dir)
|
||||||
|
logger.info(f"Created static directory: {static_dir}")
|
||||||
|
|
||||||
urls = (
|
urls = (
|
||||||
'/sse/(.+)', 'SSEHandler', # 修改路由以接收用户ID
|
'/sse/(.+)', 'SSEHandler',
|
||||||
|
'/poll/(.+)', 'PollHandler',
|
||||||
'/message', 'MessageHandler',
|
'/message', 'MessageHandler',
|
||||||
'/chat', 'ChatHandler',
|
'/chat', 'ChatHandler',
|
||||||
|
'/assets/(.*)', 'AssetsHandler', # 匹配 /static/任何路径
|
||||||
)
|
)
|
||||||
port = conf().get("web_port", 9899)
|
port = conf().get("web_port", 9899)
|
||||||
app = web.application(urls, globals(), autoreload=False)
|
app = web.application(urls, globals(), autoreload=False)
|
||||||
web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
|
web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
|
||||||
|
|
||||||
|
def poll_messages(self, user_id):
|
||||||
|
"""Poll for new messages."""
|
||||||
|
messages = []
|
||||||
|
|
||||||
|
if user_id in self.message_queues:
|
||||||
|
while not self.message_queues[user_id].empty():
|
||||||
|
messages.append(self.message_queues[user_id].get_nowait())
|
||||||
|
|
||||||
|
return json.dumps(messages)
|
||||||
|
|
||||||
|
|
||||||
class SSEHandler:
|
class SSEHandler:
|
||||||
def GET(self, user_id):
|
def GET(self, user_id):
|
||||||
@@ -200,4 +236,59 @@ class MessageHandler:
|
|||||||
|
|
||||||
class ChatHandler:
|
class ChatHandler:
|
||||||
def GET(self):
|
def GET(self):
|
||||||
return WebChannel().chat_page()
|
# 正常返回聊天页面
|
||||||
|
file_path = os.path.join(os.path.dirname(__file__), 'chat.html')
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
|
|
||||||
|
# 添加轮询处理器
|
||||||
|
class PollHandler:
|
||||||
|
def GET(self, user_id):
|
||||||
|
web.header('Content-Type', 'application/json')
|
||||||
|
return WebChannel().poll_messages(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
class AssetsHandler:
|
||||||
|
def GET(self, file_path): # 修改默认参数
|
||||||
|
try:
|
||||||
|
# 如果请求是/static/,需要处理
|
||||||
|
if file_path == '':
|
||||||
|
# 返回目录列表...
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 获取当前文件的绝对路径
|
||||||
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
static_dir = os.path.join(current_dir, 'static')
|
||||||
|
|
||||||
|
# 打印调试信息
|
||||||
|
logger.info(f"Current directory: {current_dir}")
|
||||||
|
logger.info(f"Static directory: {static_dir}")
|
||||||
|
logger.info(f"Requested file: {file_path}")
|
||||||
|
|
||||||
|
full_path = os.path.normpath(os.path.join(static_dir, file_path))
|
||||||
|
|
||||||
|
# 安全检查:确保请求的文件在static目录内
|
||||||
|
if not os.path.abspath(full_path).startswith(os.path.abspath(static_dir)):
|
||||||
|
logger.error(f"Security check failed for path: {full_path}")
|
||||||
|
raise web.notfound()
|
||||||
|
|
||||||
|
if not os.path.exists(full_path) or not os.path.isfile(full_path):
|
||||||
|
logger.error(f"File not found: {full_path}")
|
||||||
|
raise web.notfound()
|
||||||
|
|
||||||
|
# 设置正确的Content-Type
|
||||||
|
content_type = mimetypes.guess_type(full_path)[0]
|
||||||
|
if content_type:
|
||||||
|
web.header('Content-Type', content_type)
|
||||||
|
else:
|
||||||
|
# 默认为二进制流
|
||||||
|
web.header('Content-Type', 'application/octet-stream')
|
||||||
|
|
||||||
|
# 读取并返回文件内容
|
||||||
|
with open(full_path, 'rb') as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error serving static file: {e}", exc_info=True) # 添加更详细的错误信息
|
||||||
|
raise web.notfound()
|
||||||
|
|||||||
Reference in New Issue
Block a user