app.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /** @jsxImportSource https://esm.d8d.fun/hono@4.7.4/jsx */
  2. import { Hono } from 'hono'
  3. import { Auth } from '@d8d-appcontainer/auth'
  4. import type { User as AuthUser } from '@d8d-appcontainer/auth'
  5. import React from 'hono/jsx'
  6. import type { FC } from 'hono/jsx'
  7. import { cors } from 'hono/cors'
  8. import type { Context as HonoContext } from 'hono'
  9. import { serveStatic } from 'hono/deno'
  10. import { APIClient } from '@d8d-appcontainer/api'
  11. import debug from "debug"
  12. import dayjs from 'dayjs';
  13. import utc from 'dayjs/plugin/utc';
  14. import type { SystemSettingRecord, GlobalConfig } from '../client/share/types.ts';
  15. import { SystemSettingKey, OssType, MapMode } from '../client/share/types.ts';
  16. import {
  17. createKnowInfoRoutes,
  18. createFileCategoryRoutes,
  19. createFileUploadRoutes,
  20. createThemeRoutes,
  21. createSystemSettingsRoutes,
  22. } from "./routes_sys.ts";
  23. import {
  24. createMapRoutes,
  25. } from "./routes_maps.ts";
  26. import {
  27. createChartRoutes,
  28. } from "./routes_charts.ts";
  29. // 导入基础路由
  30. import { createAuthRoutes } from "./routes_auth.ts";
  31. import { createUserRoutes } from "./routes_users.ts";
  32. import { createMessagesRoutes } from "./routes_messages.ts";
  33. import { createMigrationsRoutes } from "./routes_migrations.ts";
  34. import { createHomeRoutes } from "./routes_home.ts";
  35. dayjs.extend(utc)
  36. // 初始化debug实例
  37. const log = {
  38. app: debug('app:server'),
  39. auth: debug('auth:server'),
  40. api: debug('api:server'),
  41. debug: debug('debug:server')
  42. }
  43. const GLOBAL_CONFIG: GlobalConfig = {
  44. OSS_BASE_URL: Deno.env.get('OSS_BASE_URL') || 'https://d8d-appcontainer-user.oss-cn-beijing.aliyuncs.com',
  45. OSS_TYPE: Deno.env.get('OSS_TYPE') === OssType.MINIO ? OssType.MINIO : OssType.ALIYUN,
  46. API_BASE_URL: '/api',
  47. APP_NAME: Deno.env.get('APP_NAME') || '应用Starter',
  48. ENV: Deno.env.get('ENV') || 'development',
  49. DEFAULT_THEME: 'light', // 默认主题
  50. MAP_CONFIG: {
  51. KEY: Deno.env.get('AMAP_KEY') || '您的地图API密钥',
  52. VERSION: '2.0',
  53. PLUGINS: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Geolocation'],
  54. MAP_MODE: Deno.env.get('MAP_MODE') === MapMode.OFFLINE ? MapMode.OFFLINE : MapMode.ONLINE,
  55. },
  56. CHART_THEME: 'default', // 图表主题
  57. ENABLE_THEME_CONFIG: false, // 主题配置开关
  58. THEME: null
  59. };
  60. log.app.enabled = true
  61. log.auth.enabled = true
  62. log.api.enabled = true
  63. log.debug.enabled = true
  64. // 定义自定义上下文类型
  65. export interface Variables {
  66. auth: Auth
  67. user?: AuthUser
  68. apiClient: APIClient
  69. moduleDir: string
  70. systemSettings?: SystemSettingRecord
  71. }
  72. // 定义登录历史类型
  73. interface LoginHistory {
  74. id: number
  75. user_id: number
  76. login_time: string
  77. ip_address?: string
  78. user_agent?: string
  79. }
  80. // 定义仪表盘数据类型
  81. interface DashboardData {
  82. lastLogin: string
  83. loginCount: number
  84. fileCount: number
  85. userCount: number
  86. systemInfo: {
  87. version: string
  88. lastUpdate: string
  89. }
  90. }
  91. interface EsmScriptConfig {
  92. src: string
  93. href: string
  94. denoJson: string
  95. refresh: boolean
  96. prodPath?: string
  97. prodSrc?: string
  98. }
  99. // Auth实例
  100. let authInstance: Auth | null = null
  101. // 初始化Auth实例
  102. const initAuth = async (apiClient: APIClient) => {
  103. try {
  104. if (authInstance) {
  105. return authInstance
  106. }
  107. log.auth('正在初始化Auth实例')
  108. authInstance = new Auth(apiClient as any, {
  109. jwtSecret: Deno.env.get("JWT_SECRET") || 'your-jwt-secret-key',
  110. initialUsers: [],
  111. storagePrefix: '',
  112. userTable: 'users',
  113. fieldNames: {
  114. id: 'id',
  115. username: 'username',
  116. password: 'password',
  117. phone: 'phone',
  118. email: 'email',
  119. is_disabled: 'is_disabled',
  120. is_deleted: 'is_deleted'
  121. },
  122. tokenExpiry: 24 * 60 * 60,
  123. refreshTokenExpiry: 7 * 24 * 60 * 60
  124. })
  125. log.auth('Auth实例初始化完成')
  126. return authInstance
  127. } catch (error) {
  128. log.auth('Auth初始化失败:', error)
  129. throw error
  130. }
  131. }
  132. // 初始化系统设置
  133. const initSystemSettings = async (apiClient: APIClient) => {
  134. try {
  135. const systemSettings = await apiClient.database.table('system_settings')
  136. .select()
  137. // 将系统设置转换为键值对形式
  138. const settings = systemSettings.reduce((acc: Record<string, any>, setting: any) => {
  139. acc[setting.key] = setting.value
  140. return acc
  141. }, {}) as SystemSettingRecord
  142. // 更新全局配置
  143. if (settings[SystemSettingKey.SITE_NAME]) {
  144. GLOBAL_CONFIG.APP_NAME = String(settings[SystemSettingKey.SITE_NAME])
  145. }
  146. // 设置其他全局配置项
  147. if (settings[SystemSettingKey.SITE_FAVICON]) {
  148. GLOBAL_CONFIG.DEFAULT_THEME = String(settings[SystemSettingKey.SITE_FAVICON])
  149. }
  150. if (settings[SystemSettingKey.SITE_LOGO]) {
  151. GLOBAL_CONFIG.MAP_CONFIG.KEY = String(settings[SystemSettingKey.SITE_LOGO])
  152. }
  153. if (settings[SystemSettingKey.SITE_DESCRIPTION]) {
  154. GLOBAL_CONFIG.CHART_THEME = String(settings[SystemSettingKey.SITE_DESCRIPTION])
  155. }
  156. // 设置主题配置开关
  157. if (settings[SystemSettingKey.ENABLE_THEME_CONFIG]) {
  158. GLOBAL_CONFIG.ENABLE_THEME_CONFIG = settings[SystemSettingKey.ENABLE_THEME_CONFIG] === 'true'
  159. }
  160. // 查询ID1管理员的主题配置
  161. const adminTheme = await apiClient.database.table('theme_settings')
  162. .where('user_id', 1)
  163. .first()
  164. if (adminTheme) {
  165. GLOBAL_CONFIG.THEME = adminTheme.settings
  166. }
  167. return settings
  168. } catch (error) {
  169. log.app('获取系统设置失败:', error)
  170. return {} as SystemSettingRecord
  171. }
  172. }
  173. // 中间件:验证认证
  174. const withAuth = async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
  175. try {
  176. const auth = c.get('auth')
  177. const token = c.req.header('Authorization')?.replace('Bearer ', '')
  178. if (token) {
  179. const userData = await auth.verifyToken(token)
  180. if (userData) {
  181. c.set('user', userData)
  182. await next()
  183. return
  184. }
  185. }
  186. return c.json({ error: '未授权' }, 401)
  187. } catch (error) {
  188. log.auth('认证失败:', error)
  189. return c.json({ error: '无效凭证' }, 401)
  190. }
  191. }
  192. // 导出withAuth类型定义
  193. export type WithAuth = typeof withAuth;
  194. // 定义模块参数接口
  195. interface ModuleParams {
  196. apiClient: APIClient
  197. app: Hono<{ Variables: Variables }>
  198. moduleDir: string
  199. }
  200. export default function({ apiClient, app, moduleDir }: ModuleParams) {
  201. const honoApp = app
  202. // 添加CORS中间件
  203. honoApp.use('/*', cors())
  204. // 创建API路由
  205. const api = new Hono<{ Variables: Variables }>()
  206. // // 使用数据库中间件
  207. // api.use('/*', withDatabase)
  208. // 设置环境变量
  209. api.use('*', async (c, next) => {
  210. c.set('apiClient', apiClient)
  211. c.set('moduleDir', moduleDir)
  212. c.set('auth', await initAuth(apiClient))
  213. c.set('systemSettings', await initSystemSettings(apiClient))
  214. await next()
  215. })
  216. // 查询仪表盘数据
  217. api.get('/dashboard', withAuth, async (c) => {
  218. try {
  219. const user = c.get('user')!
  220. const apiClient = c.get('apiClient')
  221. const lastLogin = await apiClient.database.table('login_history')
  222. .where('user_id', user.id)
  223. .orderBy('login_time', 'desc')
  224. .limit(1)
  225. .first()
  226. // 获取登录总次数
  227. const loginCount = await apiClient.database.table('login_history')
  228. .where('user_id', user.id)
  229. .count()
  230. // 获取系统数据统计
  231. const fileCount = await apiClient.database.table('file_library')
  232. .where('is_deleted', 0)
  233. .count()
  234. const userCount = await apiClient.database.table('users')
  235. .where('is_deleted', 0)
  236. .count()
  237. // 返回仪表盘数据
  238. const dashboardData: DashboardData = {
  239. lastLogin: lastLogin ? lastLogin.login_time : new Date().toISOString(),
  240. loginCount: loginCount,
  241. fileCount: Number(fileCount),
  242. userCount: Number(userCount),
  243. systemInfo: {
  244. version: '1.0.0',
  245. lastUpdate: new Date().toISOString()
  246. }
  247. }
  248. return c.json(dashboardData)
  249. } catch (error) {
  250. log.api('获取仪表盘数据失败:', error)
  251. return c.json({ error: '获取仪表盘数据失败' }, 500)
  252. }
  253. })
  254. // 注册基础路由
  255. api.route('/auth', createAuthRoutes(withAuth))
  256. api.route('/users', createUserRoutes(withAuth))
  257. api.route('/know-info', createKnowInfoRoutes(withAuth))
  258. api.route('/upload', createFileUploadRoutes(withAuth)) // 添加文件上传路由
  259. api.route('/file-categories', createFileCategoryRoutes(withAuth)) // 添加文件分类管理路由
  260. api.route('/theme', createThemeRoutes(withAuth)) // 添加主题设置路由
  261. api.route('/charts', createChartRoutes(withAuth)) // 添加图表数据路由
  262. api.route('/map', createMapRoutes(withAuth)) // 添加地图数据路由
  263. api.route('/settings', createSystemSettingsRoutes(withAuth)) // 添加系统设置路由
  264. api.route('/messages', createMessagesRoutes(withAuth)) // 添加消息路由
  265. api.route('/migrations', createMigrationsRoutes(withAuth)) // 添加数据库迁移路由
  266. api.route('/home', createHomeRoutes(withAuth)) // 添加首页路由
  267. // 注册API路由
  268. honoApp.route('/api', api)
  269. // 首页路由 - SSR
  270. honoApp.get('/', async (c: HonoContext) => {
  271. const systemName = GLOBAL_CONFIG.APP_NAME
  272. return c.html(
  273. <html>
  274. <head>
  275. <title>{systemName}</title>
  276. <meta charset="UTF-8" />
  277. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  278. <script src="https://cdn.tailwindcss.com"></script>
  279. </head>
  280. <body>
  281. <div className="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
  282. <div className="max-w-md w-full space-y-8">
  283. {/* 系统介绍区域 */}
  284. <div className="text-center">
  285. <h1 className="text-4xl font-bold text-gray-900 mb-4">
  286. {systemName}
  287. </h1>
  288. <p className="text-lg text-gray-600 mb-8">
  289. 全功能应用Starter
  290. </p>
  291. <p className="text-base text-gray-500 mb-8">
  292. 这是一个基于Hono和React的应用Starter,提供了用户认证、文件管理、图表分析、地图集成和主题切换等常用功能。
  293. </p>
  294. </div>
  295. {/* 管理入口按钮 */}
  296. <div className="space-y-4">
  297. <a
  298. href="/admin"
  299. className="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-lg font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
  300. >
  301. 进入管理后台
  302. </a>
  303. {/* 移动端入口按钮 */}
  304. <a
  305. href="/mobile"
  306. className="w-full flex justify-center py-3 px-4 border border-blue-600 rounded-md shadow-sm text-lg font-medium text-blue-600 bg-white hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
  307. >
  308. 进入移动端
  309. </a>
  310. </div>
  311. </div>
  312. </div>
  313. </body>
  314. </html>
  315. )
  316. })
  317. // 创建一个函数,用于生成包含全局配置的HTML页面
  318. const createHtmlWithConfig = (scriptConfig: EsmScriptConfig, title = '应用Starter') => {
  319. return (c: HonoContext) => {
  320. const isProd = GLOBAL_CONFIG.ENV === 'production';
  321. return c.html(
  322. <html lang="zh-CN">
  323. <head>
  324. <meta charset="UTF-8" />
  325. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  326. <title>{title}</title>
  327. {isProd ? (
  328. <script type="module" src={scriptConfig.prodSrc || `/client_dist/${scriptConfig.prodPath}`}></script>
  329. ) : (
  330. <script src={scriptConfig.src} href={scriptConfig.href} deno-json={scriptConfig.denoJson} refresh={scriptConfig.refresh}></script>
  331. )}
  332. {isProd ? (<script src="/tailwindcss@3.4.16/index.js"></script>) : (<script src="https://cdn.tailwindcss.com"></script>)}
  333. <script dangerouslySetInnerHTML={{ __html: `window.CONFIG = ${JSON.stringify(GLOBAL_CONFIG)};` }} />
  334. {!isProd && (
  335. <>
  336. <script src="https://ai-oss.d8d.fun/umd/vconsole.3.15.1.min.js"></script>
  337. <script dangerouslySetInnerHTML={{ __html: `
  338. const urlParams = new URLSearchParams(window.location.search);
  339. if (urlParams.has('vconsole')) {
  340. var vConsole = new VConsole({
  341. theme: urlParams.get('vconsole_theme') || 'light',
  342. onReady: function() {
  343. console.log('vConsole is ready');
  344. }
  345. });
  346. }
  347. `}} />
  348. </>
  349. )}
  350. </head>
  351. <body className="bg-gray-50">
  352. <div id="root"></div>
  353. </body>
  354. </html>
  355. )
  356. }
  357. }
  358. // 后台管理路由
  359. honoApp.get('/admin', createHtmlWithConfig({
  360. src: "https://esm.d8d.fun/xb",
  361. href: "/client/admin/web_app.tsx",
  362. denoJson: "/deno.json",
  363. refresh: true,
  364. prodPath: "admin/web_app.js"
  365. }, GLOBAL_CONFIG.APP_NAME))
  366. honoApp.get('/admin/*', createHtmlWithConfig({
  367. src: "https://esm.d8d.fun/xb",
  368. href: "/client/admin/web_app.tsx",
  369. denoJson: "/deno.json",
  370. refresh: true,
  371. prodPath: "admin/web_app.js"
  372. }, GLOBAL_CONFIG.APP_NAME))
  373. // 移动端路由
  374. honoApp.get('/mobile', createHtmlWithConfig({
  375. src: "https://esm.d8d.fun/xb",
  376. href: "/client/mobile/mobile_app.tsx",
  377. denoJson: "/deno.json",
  378. refresh: true,
  379. prodPath: "mobile/mobile_app.js"
  380. }, GLOBAL_CONFIG.APP_NAME))
  381. honoApp.get('/mobile/*', createHtmlWithConfig({
  382. src: "https://esm.d8d.fun/xb",
  383. href: "/client/mobile/mobile_app.tsx",
  384. denoJson: "/deno.json",
  385. refresh: true,
  386. prodPath: "mobile/mobile_app.js"
  387. }, GLOBAL_CONFIG.APP_NAME))
  388. const staticRoutes = serveStatic({
  389. root: moduleDir,
  390. onFound: async (path: string, c: HonoContext) => {
  391. const fileExt = path.split('.').pop()?.toLowerCase()
  392. if (fileExt === 'tsx' || fileExt === 'ts') {
  393. c.header('Content-Type', 'text/typescript; charset=utf-8')
  394. } else if (fileExt === 'js' || fileExt === 'mjs') {
  395. c.header('Content-Type', 'application/javascript; charset=utf-8')
  396. } else if (fileExt === 'json') {
  397. c.header('Content-Type', 'application/json; charset=utf-8')
  398. } else if (fileExt === 'html') {
  399. c.header('Content-Type', 'text/html; charset=utf-8')
  400. } else if (fileExt === 'css') {
  401. c.header('Content-Type', 'text/css; charset=utf-8')
  402. } else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExt || '')) {
  403. c.header('Content-Type', `image/${fileExt}`)
  404. }
  405. const fileInfo = await Deno.stat(path)
  406. c.header('Last-Modified', fileInfo.mtime?.toUTCString() ?? new Date().toUTCString())
  407. },
  408. })
  409. // 静态资源路由
  410. honoApp.get('/deno.json', staticRoutes)
  411. honoApp.get('/client/*', staticRoutes)
  412. honoApp.get('/amap/*', staticRoutes)
  413. honoApp.get('/tailwindcss@3.4.16/*', staticRoutes)
  414. honoApp.get('/client_dist/*', staticRoutes)
  415. return honoApp
  416. }