app.tsx 15 KB

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