app.tsx 17 KB

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