app.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. import { migrations } from './migrations.ts';
  30. // 导入基础路由
  31. import { createAuthRoutes } from "./routes_auth.ts";
  32. import { createUserRoutes } from "./routes_users.ts";
  33. import { createMessagesRoutes } from "./routes_messages.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 initDatabase = async (apiClient: APIClient) => {
  174. try {
  175. log.app('正在执行数据库迁移...')
  176. const migrationsResult = await apiClient.database.executeLiveMigrations(migrations)
  177. // log.app('数据库迁移完成 %O',migrationsResult)
  178. log.app('数据库迁移完成')
  179. } catch (error) {
  180. log.app('数据库迁移失败:', error)
  181. }
  182. }
  183. // 中间件:数据库初始化
  184. const withDatabase = async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
  185. try {
  186. const apiClient = c.get('apiClient')
  187. await initDatabase(apiClient)
  188. await next()
  189. } catch (error) {
  190. log.api('数据库操作失败:', error)
  191. return c.json({ error: '数据库操作失败' }, 500)
  192. }
  193. }
  194. // 中间件:验证认证
  195. const withAuth = async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
  196. try {
  197. const auth = c.get('auth')
  198. const token = c.req.header('Authorization')?.replace('Bearer ', '')
  199. if (token) {
  200. const userData = await auth.verifyToken(token)
  201. if (userData) {
  202. c.set('user', userData)
  203. await next()
  204. return
  205. }
  206. }
  207. return c.json({ error: '未授权' }, 401)
  208. } catch (error) {
  209. log.auth('认证失败:', error)
  210. return c.json({ error: '无效凭证' }, 401)
  211. }
  212. }
  213. // 导出withAuth类型定义
  214. export type WithAuth = typeof withAuth;
  215. // 定义模块参数接口
  216. interface ModuleParams {
  217. apiClient: APIClient
  218. app: Hono<{ Variables: Variables }>
  219. moduleDir: string
  220. }
  221. export default function({ apiClient, app, moduleDir }: ModuleParams) {
  222. const honoApp = app
  223. // 添加CORS中间件
  224. honoApp.use('/*', cors())
  225. // 创建API路由
  226. const api = new Hono<{ Variables: Variables }>()
  227. // 设置环境变量
  228. api.use('*', async (c, next) => {
  229. c.set('apiClient', apiClient)
  230. c.set('moduleDir', moduleDir)
  231. c.set('auth', await initAuth(apiClient))
  232. c.set('systemSettings', await initSystemSettings(apiClient))
  233. await next()
  234. })
  235. // 使用数据库中间件
  236. api.use('/', withDatabase)
  237. // 查询仪表盘数据
  238. api.get('/dashboard', withAuth, async (c) => {
  239. try {
  240. const user = c.get('user')!
  241. const apiClient = c.get('apiClient')
  242. const lastLogin = await apiClient.database.table('login_history')
  243. .where('user_id', user.id)
  244. .orderBy('login_time', 'desc')
  245. .limit(1)
  246. .first()
  247. // 获取登录总次数
  248. const loginCount = await apiClient.database.table('login_history')
  249. .where('user_id', user.id)
  250. .count()
  251. // 获取系统数据统计
  252. const fileCount = await apiClient.database.table('file_library')
  253. .where('is_deleted', 0)
  254. .count()
  255. const userCount = await apiClient.database.table('users')
  256. .where('is_deleted', 0)
  257. .count()
  258. // 返回仪表盘数据
  259. const dashboardData: DashboardData = {
  260. lastLogin: lastLogin ? lastLogin.login_time : new Date().toISOString(),
  261. loginCount: loginCount,
  262. fileCount: Number(fileCount),
  263. userCount: Number(userCount),
  264. systemInfo: {
  265. version: '1.0.0',
  266. lastUpdate: new Date().toISOString()
  267. }
  268. }
  269. return c.json(dashboardData)
  270. } catch (error) {
  271. log.api('获取仪表盘数据失败:', error)
  272. return c.json({ error: '获取仪表盘数据失败' }, 500)
  273. }
  274. })
  275. // 注册基础路由
  276. api.route('/auth', createAuthRoutes(withAuth))
  277. api.route('/users', createUserRoutes(withAuth))
  278. api.route('/know-info', createKnowInfoRoutes(withAuth))
  279. api.route('/upload', createFileUploadRoutes(withAuth)) // 添加文件上传路由
  280. api.route('/file-categories', createFileCategoryRoutes(withAuth)) // 添加文件分类管理路由
  281. api.route('/theme', createThemeRoutes(withAuth)) // 添加主题设置路由
  282. api.route('/charts', createChartRoutes(withAuth)) // 添加图表数据路由
  283. api.route('/map', createMapRoutes(withAuth)) // 添加地图数据路由
  284. api.route('/settings', createSystemSettingsRoutes(withAuth)) // 添加系统设置路由
  285. api.route('/messages', createMessagesRoutes(withAuth)) // 添加消息路由
  286. // 注册API路由
  287. honoApp.route('/api', api)
  288. // 首页路由 - SSR
  289. honoApp.get('/', async (c: HonoContext) => {
  290. const systemName = GLOBAL_CONFIG.APP_NAME
  291. return c.html(
  292. <html>
  293. <head>
  294. <title>{systemName}</title>
  295. <meta charset="UTF-8" />
  296. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  297. <script src="https://cdn.tailwindcss.com"></script>
  298. </head>
  299. <body>
  300. <div className="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
  301. <div className="max-w-md w-full space-y-8">
  302. {/* 系统介绍区域 */}
  303. <div className="text-center">
  304. <h1 className="text-4xl font-bold text-gray-900 mb-4">
  305. {systemName}
  306. </h1>
  307. <p className="text-lg text-gray-600 mb-8">
  308. 全功能应用Starter
  309. </p>
  310. <p className="text-base text-gray-500 mb-8">
  311. 这是一个基于Hono和React的应用Starter,提供了用户认证、文件管理、图表分析、地图集成和主题切换等常用功能。
  312. </p>
  313. </div>
  314. {/* 管理入口按钮 */}
  315. <div className="space-y-4">
  316. <a
  317. href="/admin"
  318. 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"
  319. >
  320. 进入管理后台
  321. </a>
  322. {/* 移动端入口按钮 */}
  323. <a
  324. href="/mobile"
  325. 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"
  326. >
  327. 进入移动端
  328. </a>
  329. </div>
  330. </div>
  331. </div>
  332. </body>
  333. </html>
  334. )
  335. })
  336. // 创建一个函数,用于生成包含全局配置的HTML页面
  337. const createHtmlWithConfig = (scriptConfig: EsmScriptConfig, title = '应用Starter') => {
  338. return (c: HonoContext) => {
  339. const isProd = GLOBAL_CONFIG.ENV === 'production';
  340. return c.html(
  341. <html lang="zh-CN">
  342. <head>
  343. <meta charset="UTF-8" />
  344. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  345. <title>{title}</title>
  346. {isProd ? (
  347. <script type="module" src={scriptConfig.prodSrc || `/client_dist/${scriptConfig.prodPath}`}></script>
  348. ) : (
  349. <script src={scriptConfig.src} href={scriptConfig.href} deno-json={scriptConfig.denoJson} refresh={scriptConfig.refresh}></script>
  350. )}
  351. {isProd ? (<script src="/tailwindcss@3.4.16/index.js"></script>) : (<script src="https://cdn.tailwindcss.com"></script>)}
  352. <script dangerouslySetInnerHTML={{ __html: `window.CONFIG = ${JSON.stringify(GLOBAL_CONFIG)};` }} />
  353. {!isProd && (
  354. <>
  355. <script src="https://ai-oss.d8d.fun/umd/vconsole.3.15.1.min.js"></script>
  356. <script dangerouslySetInnerHTML={{ __html: `
  357. const urlParams = new URLSearchParams(window.location.search);
  358. if (urlParams.has('vconsole')) {
  359. var vConsole = new VConsole({
  360. theme: urlParams.get('vconsole_theme') || 'light',
  361. onReady: function() {
  362. console.log('vConsole is ready');
  363. }
  364. });
  365. }
  366. `}} />
  367. </>
  368. )}
  369. </head>
  370. <body className="bg-gray-50">
  371. <div id="root"></div>
  372. </body>
  373. </html>
  374. )
  375. }
  376. }
  377. // 后台管理路由
  378. honoApp.get('/admin', createHtmlWithConfig({
  379. src: "https://esm.d8d.fun/xb",
  380. href: "/client/admin/web_app.tsx",
  381. denoJson: "/client/admin/deno.json",
  382. refresh: true,
  383. prodPath: "admin/web_app.js"
  384. }, GLOBAL_CONFIG.APP_NAME))
  385. honoApp.get('/admin/*', createHtmlWithConfig({
  386. src: "https://esm.d8d.fun/xb",
  387. href: "/client/admin/web_app.tsx",
  388. denoJson: "/client/admin/deno.json",
  389. refresh: true,
  390. prodPath: "admin/web_app.js"
  391. }, GLOBAL_CONFIG.APP_NAME))
  392. // 移动端路由
  393. honoApp.get('/mobile', createHtmlWithConfig({
  394. src: "https://esm.d8d.fun/xb",
  395. href: "/client/mobile/mobile_app.tsx",
  396. denoJson: "/client/mobile/deno.json",
  397. refresh: true,
  398. prodPath: "mobile/mobile_app.js"
  399. }, GLOBAL_CONFIG.APP_NAME))
  400. honoApp.get('/mobile/*', createHtmlWithConfig({
  401. src: "https://esm.d8d.fun/xb",
  402. href: "/client/mobile/mobile_app.tsx",
  403. denoJson: "/client/mobile/deno.json",
  404. refresh: true,
  405. prodPath: "mobile/mobile_app.js"
  406. }, GLOBAL_CONFIG.APP_NAME))
  407. const staticRoutes = serveStatic({
  408. root: moduleDir,
  409. onFound: async (path: string, c: HonoContext) => {
  410. const fileExt = path.split('.').pop()?.toLowerCase()
  411. if (fileExt === 'tsx' || fileExt === 'ts') {
  412. c.header('Content-Type', 'text/typescript; charset=utf-8')
  413. } else if (fileExt === 'js' || fileExt === 'mjs') {
  414. c.header('Content-Type', 'application/javascript; charset=utf-8')
  415. } else if (fileExt === 'json') {
  416. c.header('Content-Type', 'application/json; charset=utf-8')
  417. } else if (fileExt === 'html') {
  418. c.header('Content-Type', 'text/html; charset=utf-8')
  419. } else if (fileExt === 'css') {
  420. c.header('Content-Type', 'text/css; charset=utf-8')
  421. } else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExt || '')) {
  422. c.header('Content-Type', `image/${fileExt}`)
  423. }
  424. const fileInfo = await Deno.stat(path)
  425. c.header('Last-Modified', fileInfo.mtime?.toUTCString() ?? new Date().toUTCString())
  426. },
  427. })
  428. // 静态资源路由
  429. honoApp.get('/client/*', staticRoutes)
  430. honoApp.get('/amap/*', staticRoutes)
  431. honoApp.get('/tailwindcss@3.4.16/*', staticRoutes)
  432. honoApp.get('/client_dist/*', staticRoutes)
  433. return honoApp
  434. }