diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..29a99f6 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,81 @@ +name: Build and Release + +on: + push: + tags: + - "v*.*.*" + +jobs: + # linux_build: + # permissions: write-all + # runs-on: ubuntu-latest + + # steps: + # - name: Checkout code + # uses: actions/checkout@v3 + + # - name: Set up Node.js ${{ matrix.node-version }} + # uses: actions/setup-node@v3 + # with: + # node-version: ${{ matrix.node-version }} + + # - name: Set up Rust + # uses: actions-rs/toolchain@v1 + # with: + # toolchain: stable + + # - name: Build + # working-directory: ./ + # run: rustc -V && bash ./build.sh && ls -al + + # - uses: ncipollo/release-action@v1 + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # with: + # artifacts: "lsys.tar.gz" + # allowUpdates: true + # token: ${{ secrets.GITHUB_TOKEN }} + # name: ${{ github.event.head_commit.message }} + # prerelease: true + # tag: ${{ github.ref }} + # body: tag version ${{ github.ref }} + # skipIfReleaseExists: true + + windows_build: + permissions: write-all + runs-on: windows-latest + steps: + - uses: actions/checkout@v2 + + - name: Set up Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + + - name: Set up Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + + - name: Build release + run: ./build.cmd + + - name: Get current tag + id: get_tag + run: | + $tag = $env:GITHUB_REF -replace 'refs/tags/', '' + Write-Host "##[set-output name=tag;]$tag" + + - uses: ncipollo/release-action@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + artifacts: "lsys.zip" + token: ${{ secrets.GITHUB_TOKEN }} + name: ${{ steps.get_tag.outputs.tag }} + prerelease: true + tag: ${{ github.ref }} + body: | + 版本说明: ${{ github.event.head_commit.message }} + 文件说明: lsys.zip 为 windows x64 下编译版本,其他版本自行编译。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d1510b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/.idea +/.vscode +/.history +dump.rdb +sdk/go/examples/sub_app/__debug_* +sdk/go/.vscode/launch.json +/server/*/.idea/* +/server/.idea/* +/build/* +lsys.tar.gz +lsys.zip \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bdf5566 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,36 @@ +FROM rust:latest as rust_rust_builder +WORKDIR /usr/src/lsys-web +COPY ./server . +RUN cargo build -r && sed -i 's|../../../ui/public/|./ui/|g' ./usr/src/lsys-web/examples/lsys-actix-web/config/app.toml + +FROM node:18-buster as node_builder +WORKDIR /usr/src/lsys-web +COPY ./ui . +RUN cd ./web && npm run build && cd .. && cd ./web && npm run build + +FROM debian:buster-slim +WORKDIR /usr/local/lsys-web +RUN apt-get update && apt-get install -y libssl1.1 && rm -rf /var/lib/apt/lists/* + +ENV \ + APP_HOST=127.0.0.1 \ + APP_PORT=80 \ + #APP_SSL_PORT=443 + LOG_LEVEL=sqlx_core=info,lsys_sender=debug,axtix_web=debug,actix=info,mio=error,lsys_user=trace,lsys_web=trace,lsys_core=trace,lsys_user=trace,lsys_rbac=trace,lsys_docs=trace,lsys_actix_web=trace,sqlx=trace,redis=debug \ + LOG_DIR="logs" \ + LOG_NAME="std::out" \ + #数据库配置 \ + DATABASE_URL="mysql://root:000@127.0.0.1:3306/test2" \ + #公共表前缀 + DATABASE_TABLE_PREFIX="yaf_" \ + #redis 配置 + REDIS_URL="redis://127.0.0.1/" + +COPY --from=rust_builder /usr/src/lsys-web/examples/lsys-actix-web/static /usr/local/lsys-web/ +COPY --from=rust_builder /usr/src/lsys-web/examples/lsys-actix-web/config /usr/local/lsys-web/ +COPY --from=rust_builder /usr/src/lsys-web/examples/lsys-actix-web/locale /usr/local/lsys-web/ +COPY --from=rust_builder /usr/src/lsys-web/examples/lsys-actix-web/data /usr/local/lsys-web/ +COPY --from=rust_builder /usr/src/lsys-web/examples/lsys-actix-web/.env /usr/local/lsys-web/.env +COPY --from=rust_builder /usr/src/lsys-web/examples/target/release/lsys-actix-web /usr/local/lsys-web/lsys-actix-web +COPY --from=node_builder /usr/src/lsys-web/public /usr/local/lsys-web/ui +CMD ["/usr/local/lsys-web/lsys-actix-web"] \ No newline at end of file diff --git a/README.MD b/README.MD index c18cce8..4824e5a 100644 --- a/README.MD +++ b/README.MD @@ -1,4 +1,4 @@ -### rust实现的`面向内部应用的应用管理中心`实现 +### rust实现的 `内部应用应用管理中心` > 适用场景: > 1. 当你使用rust开发web应用时,使用本项目二次开发可以减少重复工作量。 @@ -10,49 +10,53 @@ > 在线示例: https://lsys.cc/ [账号:aaaaa 密码:000000] -##### [后端服务](server) 安装 +#### 配置跟编译 -1. 编译 【中途有失败再次执行】 +1. 修改UI访问服务器地址 ``` -cd server && cargo build -r && cd .. +./ui/web/config.json #修改配置 +./ui/wap/config.json #修改配置 ``` -2. 导入SQL到数据库 -``` -导入 ./server/assets/tables.sql 到MYSQL -``` +2. 执行编译 -3. 修改你的监听端口,REDIS,MYSQL等 -> [./server/examples/lsys-actix-web/.env 会覆盖./server/examples/lsys-actix-web/config/] +> 编译生成文件在 `./build` 目录中,同时生成 `./build` 目录的压缩包 +> windows ``` -./server/examples/lsys-actix-web/.env +.\build.cmd #生成 lsys.zip ``` -4. 执行 启动服务 +> linux or macos ``` -cd ./server/examples/lsys-actix-web/ && ../../target/release/lsys-actix-web +bash ./build.sh #生成 lsys.tar.gz ``` +> 仅拷贝 `./build` 文件夹到你的服务器 或 把对应生成压缩包拷贝后解压,其他文件可以删除. -##### [管理UI](ui) 安装 - -1. 修改配置,设置服务地址跟jwt的token等 +3. 导入SQL到数据库 ``` -./ui/web/config.json -./ui/wap/config.json +mysql -u your_username -p your_database < ./build/assets/tables.sql #导入到你的MYSQL ``` -2. 编译 +4. 根据实际情况,对 `Redis` `Mysql` `jwt token` `日志输出` 等配置进行修改。 ``` -cd ./ui/web && npm i && npm run build && cd ../.. -cd ./ui/wap && npm i && npm run build && cd ../.. -cd .. +./build/.env #修改配置 ``` -3. 访问 http://127.0.0.1/ui/ +5. 启动服务 + +> 下载文件[2023-7-area-code.csv.gz](https://github.com/shanliu/area-db/blob/main/data/2023-7-area-code.csv.gz) 到 `build/data` 目录 + +> [可选] 下载IP文件 `IP2LOCATION-LITE-DB11.BIN` 到 `build/data/` 目录 + +> 执行 `./actix-web-dome ` 启动服务。注意:初次启动会慢一些。 + +> 可使用 `nohup ./actix-web-dome &` 后台执行 + +> 根据`.env`配置访问服务.默认地址:http://127.0.0.1:8080/ -#### 二次开发参考时序: +#### 二次开发时序参考 ##### 基于rust二次开发 diff --git a/build.cmd b/build.cmd new file mode 100644 index 0000000..f37a7d3 --- /dev/null +++ b/build.cmd @@ -0,0 +1,40 @@ +mkdir build +xcopy "README.MD" build /Y +xcopy LICENSE build /Y + +mkdir server\\examples\\lsys-actix-web\data +cd server\\examples\\lsys-actix-web +cargo version +rustc -V +cargo update +cargo build -r -vvv +cd ..\\..\\.. + +xcopy /E /I /Y server\\assets build\\assets +xcopy server\\target\\release\\lsys-actix-web.exe build /Y +xcopy /E /I /Y server\\examples\\lsys-actix-web\\config build\\config +xcopy /E /I /Y server\\examples\\lsys-actix-web\\data build\\data +xcopy /E /I /Y server\\examples\\lsys-actix-web\\locale build\\locale +xcopy /E /I /Y server\\examples\\lsys-actix-web\\static build\\static +xcopy server\\examples\\lsys-actix-web\\.env build /Y + +cd ui\\web +call npm install +call npm run build +cd ..\\.. +mkdir ui\\public +cd ui\\wap +call npm install +call npm run build +cd ..\\.. +mkdir ui\\public +xcopy /E /I /Y ui\\public build\\ui + + +powershell.exe -Command "(Get-Content -Path 'build\\config\\app.toml') | ForEach-Object { $_ -replace '../../../ui/public/', './ui/' } | Set-Content -Path 'build\\config\\app.toml'" + +cd build +powershell.exe -Command "Compress-Archive -Path './' -DestinationPath '../lsys.zip'" +cd .. + +echo The compilation was successful, please enable the service with ( ./lsys-actix-web ) to the service and access it via http://127.0.0.1:8080 diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..ecce4f3 --- /dev/null +++ b/build.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +mkdir -p build +cp -fr ./README.MD ./build +cp -fr ./LICENSE ./build +# +mkdir -p ./server/examples/lsys-actix-web/data +cd ./server/examples/lsys-actix-web && cargo build \-r && cd ../../.. +cp -fr ./server/assets ./build +cp -fr ./server/target/release/lsys-actix-web ./build +cp -fr ./server/examples/lsys-actix-web/config ./build +cp -fr ./server/examples/lsys-actix-web/data ./build +cp -fr ./server/examples/lsys-actix-web/locale ./build +cp -fr ./server/examples/lsys-actix-web/static ./build +cp -fr ./server/examples/lsys-actix-web/.env ./build +# +cd ui/web && npm i && npm run build && cd ../.. +cd ui/wap && npm i && npm run build && cd ../.. +cp -fr ./ui/public/ ./build/ui/ +# +if [ "$(uname)" = "Darwin" ]; then + sed -i '' "s|../../../ui/public/|./ui/|g" ./build/config/app.toml +else + sed -i "s|../../../ui/public/|./ui/|g" ./build/config/app.toml +fi + +cd ./build && tar -cvf ../lsys.tar.gz ./ && cd .. +# +echo -e "The compilation was successful, \ +Please start the service with ( ./lsys-actix-web ) \ +to start the service and access it via \033[1;32mhttp://127.0.0.1:8080\033[0m" diff --git a/server/Dockerfile b/server/Dockerfile deleted file mode 100644 index ad23948..0000000 --- a/server/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM rust:latest as builder -WORKDIR /usr/src/lsys-web-src -COPY . . -RUN cargo build -r - - - - -FROM debian:buster-slim -WORKDIR /usr/local/lsys-web -RUN apt-get update && apt-get install -y libssl1.1 && rm -rf /var/lib/apt/lists/* -COPY --from=builder /usr/src/lsys-web-src/examples/lsys-actix-web/.env /usr/local/lsys-web/.env -COPY --from=builder /usr/src/lsys-web-src/examples/lsys-actix-web/static /usr/local/lsys-web/static -COPY --from=builder /usr/src/lsys-web-src/examples/lsys-actix-web/config /usr/local/lsys-web/config -COPY --from=builder /usr/src/lsys-web-src/examples/lsys-actix-web/locale /usr/local/lsys-web/locale -COPY --from=builder /usr/src/lsys-web-src/examples/lsys-actix-web/data /usr/local/lsys-web/data -COPY --from=builder /usr/src/lsys-web-src/examples/target/release/lsys-actix-web /usr/local/lsys-web/lsys-actix-web -CMD ["/usr/local/lsys-web/lsys-actix-web"] \ No newline at end of file diff --git a/server/README.MD b/server/README.MD index ee6e71e..2a2bcb3 100644 --- a/server/README.MD +++ b/server/README.MD @@ -7,14 +7,14 @@ > 已实现统一登陆的oauth服务,更多的通用应用实现中。。。 -#### 开发配置 +### 开发or编译 1. 导入SQL到数据库 ``` 导入 ./assets/tables.sql 到MYSQL ``` -2. 修改你的REDIS,MYSQL等的配置 +2. 修改你的REDIS,MYSQL,jwt token等配置 > [./examples/lsys-actix-web/.env 的配置会覆盖./examples/lsys-actix-web/config/下配置] ``` @@ -24,4 +24,5 @@ 3. 启动开发环境 ``` cd ./examples/lsys-actix-web/ && cargo run -``` \ No newline at end of file +#cargo build -r && cd .. #or build +``` diff --git a/server/examples/lsys-actix-web/.env b/server/examples/lsys-actix-web/.env index a14e533..b37a243 100644 --- a/server/examples/lsys-actix-web/.env +++ b/server/examples/lsys-actix-web/.env @@ -6,6 +6,9 @@ LOG_DIR="logs" LOG_NAME="std::out" #LOG_GELF="127.0.0.1:12201" +#jwt 密钥 ,修改将导致登陆失效 +APP_JWT_KEY = "bbb" + #数据库配置 DATABASE_URL="mysql://root:000@127.0.0.1:3306/test2" #公共表前缀 diff --git a/server/examples/lsys-actix-web/config/app.toml b/server/examples/lsys-actix-web/config/app.toml index f62ea00..76491ae 100644 --- a/server/examples/lsys-actix-web/config/app.toml +++ b/server/examples/lsys-actix-web/config/app.toml @@ -22,6 +22,7 @@ rbac_cache = true ui_dir = "../../../ui/public/" #静态文件访问路径,默认:/ui/ #ui_path="/ui/" +ui_path="/" #超级管理员id root_user_id = [1] @@ -29,7 +30,7 @@ root_user_id = [1] fluent_dir = "locale/" #页面模板目录 -tpl_dir = "static" +tpl_dir = "./static" #地址库数据文件压缩包 area_code_db = "data/2023-7-area-code.csv.gz" @@ -46,8 +47,8 @@ ip_city_db = "data/IP2LOCATION-LITE-DB11.BIN" #snowflake_node_id=1 #最大31 # jwt token -app_jwt_key = "bbb" #jwt 密钥 +#app_jwt_key = "bbb" #jwt 密钥 #git doc save dir -doc_git_dir = "/tmp/" +#doc_git_dir = "/tmp/" diff --git a/server/examples/lsys-actix-web/locale/en_US/app.ftl b/server/examples/lsys-actix-web/locale/en_US/app.ftl index b88a9f4..5003314 100644 --- a/server/examples/lsys-actix-web/locale/en_US/app.ftl +++ b/server/examples/lsys-actix-web/locale/en_US/app.ftl @@ -1,3 +1,13 @@ jwt-encode-error = JWT generation error:{$msg} -wechat-parse-state-error= state error:{$msg} \ No newline at end of file +wechat-parse-state-error= state error:{$msg} + +time-format-error=Date parsing exception: {$msg} + +time-zone-error=Date time zone exception. + +area-db-error=Database exception:{$msg} +area-error=System exception:{$msg} +area-not-found=Address information not found. +areaa-store-error=Store exception:{$msg} +area-tantivy-error=Search exception:{$msg} \ No newline at end of file diff --git a/server/examples/lsys-actix-web/locale/en_US/lsys-core.ftl b/server/examples/lsys-actix-web/locale/en_US/lsys-core.ftl index f6c2f6c..ae6b48f 100644 --- a/server/examples/lsys-actix-web/locale/en_US/lsys-core.ftl +++ b/server/examples/lsys-actix-web/locale/en_US/lsys-core.ftl @@ -1,5 +1,6 @@ app-error = Send error, details:{$msg} -utf-error = String is not a valid UTF character, error details:{$msg} +utf-parse-error = String is not a valid UTF character, error details:{$msg} valid-code-tag-len = Checksum KEY[{$tag}] max length:{$max} valid-code-submit-empty = The code is not empty. -valid-code-not-match = The submitted code [{$code}] does not match. \ No newline at end of file +valid-code-not-match = The submitted code [{$code}] does not match. +wait-notify-timeout=Wait to send timeout \ No newline at end of file diff --git a/server/examples/lsys-actix-web/locale/en_US/lsys-web.ftl b/server/examples/lsys-actix-web/locale/en_US/lsys-web.ftl index 853644d..13fbecd 100644 --- a/server/examples/lsys-actix-web/locale/en_US/lsys-web.ftl +++ b/server/examples/lsys-actix-web/locale/en_US/lsys-web.ftl @@ -20,7 +20,8 @@ address-bad-area = The submitted area code does not exist. mail-bind-other-user = Mailbox is bound to another account [{$other_user_id}]. rbac-check-fail = permission check failed -system-not-found = Result does not exist +db-not-found = Result does not exist +db-error = database error:{$msg} user-old-passwrod-bad= The original password was submitted incorrectly. user-old-passwrod-empty= Please submit the original password. diff --git a/server/examples/lsys-actix-web/locale/zh_CN/app.ftl b/server/examples/lsys-actix-web/locale/zh_CN/app.ftl index 5d6afcc..2c2e236 100644 --- a/server/examples/lsys-actix-web/locale/zh_CN/app.ftl +++ b/server/examples/lsys-actix-web/locale/zh_CN/app.ftl @@ -1,3 +1,15 @@ jwt-encode-error = JWT生成错误:{$msg} wechat-parse-state-error= state 错误:{$msg} + + + +time-format-error=日期解析异常:{$msg} + +time-zone-error=日期时区异常 + +area-db-error=数据库异常:{$msg} +area-error=系统异常:{$msg} +area-not-found=地址信息未找到 +area-store-error=存储异常:{$msg} +area-tantivy-error=搜索异常:{$msg} diff --git a/server/examples/lsys-actix-web/locale/zh_CN/lsys-core.ftl b/server/examples/lsys-actix-web/locale/zh_CN/lsys-core.ftl index c835914..0edd033 100644 --- a/server/examples/lsys-actix-web/locale/zh_CN/lsys-core.ftl +++ b/server/examples/lsys-actix-web/locale/zh_CN/lsys-core.ftl @@ -1,5 +1,7 @@ app-error = 发送错误,详细:{$msg} -utf-error = 字符串非有效UTF字符,错误详细:{$msg} +utf-parse-error = 字符串非有效UTF字符,错误详细:{$msg} valid-code-tag-len = 校验码KEY[{$tag}]最大长度为:{$max} valid-code-submit-empty = 验证码不为空 valid-code-not-match = 提交的验证码[{$code}]不匹配 + +wait-notify-timeout=等待发送超时 diff --git a/server/examples/lsys-actix-web/locale/zh_CN/lsys-rbac.ftl b/server/examples/lsys-actix-web/locale/zh_CN/lsys-rbac.ftl index 0be328b..649fef2 100644 --- a/server/examples/lsys-actix-web/locale/zh_CN/lsys-rbac.ftl +++ b/server/examples/lsys-actix-web/locale/zh_CN/lsys-rbac.ftl @@ -13,4 +13,5 @@ rbac-role-miss-res = 角色[{$name}:{$id}]不存在 rbac-role-miss-res-op = 未发现的资源[{$name}:{$id}] rbac-role-bad-res-user = 非系统角色不能加非本角色用户资源,资源未:{$res},用户为:{$user_id} rbac-role-wrong-res-op = 发现系统中的[{$name}:{$id}] 的 {$res_id} 跟传入的 {$p_res_id} 不一致 -rbac-user-range-bad = 关联角色请使用专门的接口添加 \ No newline at end of file +rbac-user-range-bad = 关联角色请使用专门的接口添加 +rbac-check-fail = 权限校验失败 \ No newline at end of file diff --git a/server/examples/lsys-actix-web/locale/zh_CN/lsys-user.ftl b/server/examples/lsys-actix-web/locale/zh_CN/lsys-user.ftl index 400716f..fb25fcc 100644 --- a/server/examples/lsys-actix-web/locale/zh_CN/lsys-user.ftl +++ b/server/examples/lsys-actix-web/locale/zh_CN/lsys-user.ftl @@ -22,7 +22,7 @@ user-auth-parse-error = 解析TOKEN异常:{$msg} check-user-lock = 用户{$user}已被锁定,将在{$time}秒后恢复 -auth-user-captcha = 用户{$user}登录时提交验证错误 +auth-user-captcha = 用户{$user}登录时需要验证码 auth-user-disable = 用户{$user}已被禁用 @@ -47,5 +47,5 @@ auth-email-not-match = 邮箱[{$mail}]格式错误 auth-mobile-error = 手机号校验失败:{$msg} auth-mobile-area-error = 手机区号{$area}异常 serde-error = 序列化异常:{$msg} -utf-error = 字符串非有效UTF字符,错误详细:{$msg} +utf-parse-error = 字符串非有效UTF字符,错误详细:{$msg} not-login-empty-token = 用户未登陆:token不存在 diff --git a/server/examples/lsys-actix-web/locale/zh_CN/lsys-web.ftl b/server/examples/lsys-actix-web/locale/zh_CN/lsys-web.ftl index 7e71d29..6e1c54f 100644 --- a/server/examples/lsys-actix-web/locale/zh_CN/lsys-web.ftl +++ b/server/examples/lsys-actix-web/locale/zh_CN/lsys-web.ftl @@ -21,7 +21,8 @@ address-bad-area = 提交的区域编码不存在 mail-bind-other-user = 邮箱已绑定其他账号[{$other_user_id}] rbac-check-fail = 权限校验失败 -system-not-found = 不存在相关记录 +db-not-found = 不存在相关记录 +db-error = 数据库错误:{$msg} user-old-passwrod-bad= 提交的原密码错误 user-old-passwrod-empty= 请提交原密码 @@ -93,8 +94,6 @@ res-op-user-email=用户邮箱 res-op-user-mobile=用户手机号 res-op-user-address=用户守候地址 -res-op-view=查看 -res-op-edit=编辑 res-op-change-all=资源更改 diff --git a/server/examples/lsys-actix-web/src/handler/api/docs.rs b/server/examples/lsys-actix-web/src/handler/api/docs.rs index 1268662..2267e69 100644 --- a/server/examples/lsys-actix-web/src/handler/api/docs.rs +++ b/server/examples/lsys-actix-web/src/handler/api/docs.rs @@ -11,6 +11,7 @@ use actix_web::web::Data; use actix_web::CustomizeResponder; use actix_web::Responder; use actix_web::Result; +use lsys_core::IntoFluentMessage; use lsys_web::dao::WebDao; use lsys_web::handler::api::utils::docs_file; use lsys_web::handler::api::utils::docs_git_add; @@ -64,7 +65,7 @@ async fn docs_raw( &web_dao, ) .await - .map_err(|e| InternalError::new(e.to_string(), StatusCode::OK))?; + .map_err(|e| InternalError::new(e.to_fluent_message().default_format(), StatusCode::OK))?; debug!("read raw file:{}", &path.file_path.to_string_lossy()); let file = NamedFile::open_async(path.file_path).await?; let ftype = file.content_type().to_string(); diff --git a/server/examples/lsys-actix-web/src/handler/notify/sms.rs b/server/examples/lsys-actix-web/src/handler/notify/sms.rs index 0a40b34..182ce9b 100644 --- a/server/examples/lsys-actix-web/src/handler/notify/sms.rs +++ b/server/examples/lsys-actix-web/src/handler/notify/sms.rs @@ -4,6 +4,7 @@ use actix_http::StatusCode; use actix_web::web::{Bytes, Data}; use actix_web::{post, HttpRequest, HttpResponse}; +use lsys_core::IntoFluentMessage; use lsys_sender::dao::{AliYunNotify, CloOpenNotify, HwYunNotify, NetEaseNotify, TenYunNotify}; use lsys_web::dao::WebDao; @@ -16,7 +17,7 @@ pub(crate) async fn notify( ) -> HttpResponse { let config = match web_dao.setting.multiple.find(&None, &path.0).await { Ok(e) => e, - Err(e) => return HttpResponse::Forbidden().body(e.to_string()), + Err(e) => return HttpResponse::Forbidden().body(e.to_fluent_message().default_format()), }; let notify = &web_dao.sender_smser.smser.sms_notify; let (status, msg) = if notify.check::(&config) { diff --git a/server/examples/lsys-actix-web/src/handler/rest/app/info.rs b/server/examples/lsys-actix-web/src/handler/rest/app/info.rs index 256452f..d4016f4 100644 --- a/server/examples/lsys-actix-web/src/handler/rest/app/info.rs +++ b/server/examples/lsys-actix-web/src/handler/rest/app/info.rs @@ -9,7 +9,7 @@ use lsys_web::handler::app::{subapp_view, SubAppViewParam}; // -> 检查签名 // -> 授权查询... #[post("app")] -pub(crate) async fn app(mut rest: RestQuery) -> ResponseJsonResult { +pub(crate) async fn app_info(mut rest: RestQuery) -> ResponseJsonResult { Ok(match rest.rfc.method.as_deref() { Some("view") => { let param = rest.param::()?; diff --git a/server/examples/lsys-actix-web/src/handler/rest/app/rbac.rs b/server/examples/lsys-actix-web/src/handler/rest/app/rbac.rs index 1abbe01..aebb3f8 100644 --- a/server/examples/lsys-actix-web/src/handler/rest/app/rbac.rs +++ b/server/examples/lsys-actix-web/src/handler/rest/app/rbac.rs @@ -9,15 +9,6 @@ pub(crate) async fn access(mut rest: RestQuery) -> ResponseJsonResult()?; app_rbac_check(&rest, &rest.to_app_model().await?, param).await } - // Some("access") => { - // let param = rest.param::()?; - // subapp_rbac_access_check( - // &rest, - // &rest.rfc.to_app_model(&app_dao.app.app_dao.app).await?, - // param, - // ) - // .await - // } Some("menu") => { let param = rest.param::()?; app_rbac_menu_check(&rest, &rest.to_app_model().await?, param).await diff --git a/server/examples/lsys-actix-web/src/handler/rest/mod.rs b/server/examples/lsys-actix-web/src/handler/rest/mod.rs index 74705cc..8e15e3a 100644 --- a/server/examples/lsys-actix-web/src/handler/rest/mod.rs +++ b/server/examples/lsys-actix-web/src/handler/rest/mod.rs @@ -25,7 +25,7 @@ where app.service( scope("/rest") .service(app::access) - .service(app::app) + .service(app::app_info) .service(app::sms) .service(app::mail) .service(app::demo_app), diff --git a/server/examples/lsys-web-module-oauth/src/module/wechat_login.rs b/server/examples/lsys-web-module-oauth/src/module/wechat_login.rs index 9f8ac7a..0420be4 100644 --- a/server/examples/lsys-web-module-oauth/src/module/wechat_login.rs +++ b/server/examples/lsys-web-module-oauth/src/module/wechat_login.rs @@ -1,6 +1,6 @@ use async_trait::async_trait; -use lsys_core::{fluent_message, rand_str, RandType}; +use lsys_core::{fluent_message, rand_str, IntoFluentMessage, RandType}; use lsys_web::{ dao::{user::WebUser, RequestDao}, module::oauth::{OauthCallbackParam, OauthLogin, OauthLoginData, OauthLoginParam}, @@ -162,7 +162,12 @@ impl OauthLogin for W .single .load::(&None) .await - .map_err(|e| format!("load wechat error:{}", e))?; + .map_err(|e| { + format!( + "load wechat error:{}", + e.to_fluent_message().default_format() + ) + })?; Ok(WechatLogin::new( config.app_id.to_owned(), config.app_secret.to_owned(), diff --git a/server/lsys-app/src/dao/app/apps.rs b/server/lsys-app/src/dao/app/apps.rs index b76e8cc..23096a9 100644 --- a/server/lsys-app/src/dao/app/apps.rs +++ b/server/lsys-app/src/dao/app/apps.rs @@ -270,7 +270,7 @@ impl Apps { ) -> AppsResult<()> { if !AppStatus::Delete.eq(app.status) && !AppStatus::Ok.eq(app.status) { return Err(AppsError::System(fluent_message!("app-not-confirm", - {"name":app.name} + {"name":&app.name} ))); } if (status && AppStatus::Ok.eq(app.status)) || (!status && AppStatus::Delete.eq(app.status)) diff --git a/server/lsys-app/src/dao/app/mod.rs b/server/lsys-app/src/dao/app/mod.rs index da93910..ae975dc 100644 --- a/server/lsys-app/src/dao/app/mod.rs +++ b/server/lsys-app/src/dao/app/mod.rs @@ -5,21 +5,6 @@ use lsys_logger::dao::ChangeLogData; fn range_client_key() -> String { rand_str(RandType::LowerHex, 64) - // const BASE_STR: &str = "0123456789abcdef0123456789abcdef"; - // let mut rng = &mut rand::thread_rng(); - // String::from_utf8( - // BASE_STR - // .as_bytes() - // .choose_multiple(&mut rng, 64) - // .cloned() - // .collect(), - // ) - // .unwrap_or_else(|_| { - // format!( - // "{:x}", - // md5::compute(now_time().unwrap_or_default().to_string().as_bytes()) - // ) - // }) } mod apps; diff --git a/server/lsys-app/src/dao/app/oauth.rs b/server/lsys-app/src/dao/app/oauth.rs index 58b5857..04a2fb7 100644 --- a/server/lsys-app/src/dao/app/oauth.rs +++ b/server/lsys-app/src/dao/app/oauth.rs @@ -182,8 +182,8 @@ impl AppsOauth { return Err(AppsError::System(fluent_message!( "token-not-find", //, { - "name":app.name, - "code":code, + "name":&app.name, + "code":&code, } // "your submit token is not find" ))); @@ -248,7 +248,7 @@ impl AppsOauth { None => { if app_token.timeout < now_time().unwrap_or_default() { return Err(AppsError::System(fluent_message!("token-is-timeout" , - {"token":app_token.token} + {"token":&app_token.token} // "your submit code is timeout or wrong" ))); } @@ -308,7 +308,7 @@ impl AppsOauth { } Err(sqlx::Error::RowNotFound) => Err(AppsError::System(fluent_message!( "token-is-timeout" , - {"token":user_token_data.token} + {"token":&user_token_data.token} // "your submit token not find" ))), Err(err) => Err(err.into()), diff --git a/server/lsys-app/src/dao/app/sub_apps.rs b/server/lsys-app/src/dao/app/sub_apps.rs index 81f9f22..bd5631e 100644 --- a/server/lsys-app/src/dao/app/sub_apps.rs +++ b/server/lsys-app/src/dao/app/sub_apps.rs @@ -84,7 +84,7 @@ impl SubApps { ) -> AppsResult<()> { if *user_id == 0 { return Err(AppsError::System(fluent_message!("app-add-empty-user", - {"app":app.name} + {"app":&app.name} ))); } match Select::type_new::() @@ -298,13 +298,13 @@ impl SubApps { ) -> AppsResult { if parent_app.id == app.id { return Err(AppsError::System(fluent_message!("app-parent-add-self", - {"name":app.name} + {"name":&app.name} ))); } if sub_secret.is_empty() { return Err(AppsError::System( fluent_message!("app-parent-secret-empty", - {"name":app.name} + {"name":&app.name} ), )); } @@ -320,8 +320,8 @@ impl SubApps { sqlx::Error::RowNotFound => { AppsError::System(fluent_message!("app-parent-add-bad-user", { - "name":app.name, - "parent_name":parent_app.name, + "name":&app.name, + "parent_name":&parent_app.name, "user_id":app.user_id } // "your can't add sub app to {} ,user id [{}] is not allowed ", diff --git a/server/lsys-app/src/dao/mod.rs b/server/lsys-app/src/dao/mod.rs index a564d98..56ea484 100644 --- a/server/lsys-app/src/dao/mod.rs +++ b/server/lsys-app/src/dao/mod.rs @@ -1,73 +1,15 @@ -use lsys_core::{fluent_message, AppCoreError, FluentMessage, RemoteNotify}; +use lsys_core::{AppCoreError, RemoteNotify}; use lsys_user::dao::account::UserAccount; -use std::{ - error::Error, - fmt::{Display, Formatter}, - time::SystemTimeError, -}; - -use deadpool_redis::PoolError; - -use lsys_user::dao::account::UserAccountError; - -use redis::RedisError; use self::app::{Apps, AppsOauth, SubApps}; use lsys_logger::dao::ChangeLogger; use sqlx::{MySql, Pool}; use std::sync::Arc; pub mod app; -pub mod session; - -#[derive(Debug)] -pub enum AppsError { - Sqlx(sqlx::Error), - System(FluentMessage), - Redis(RedisError), - RedisPool(PoolError), - ScopeNotFind(FluentMessage), - UserAccount(UserAccountError), - SerdeJson(serde_json::Error), -} -impl Display for AppsError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl Error for AppsError {} - -impl From for AppsError { - fn from(err: sqlx::Error) -> Self { - AppsError::Sqlx(err) - } -} -impl From for AppsError { - fn from(err: RedisError) -> Self { - AppsError::Redis(err) - } -} -impl From for AppsError { - fn from(err: PoolError) -> Self { - AppsError::RedisPool(err) - } -} -impl From for AppsError { - fn from(err: SystemTimeError) -> Self { - AppsError::System(fluent_message!("time-error", err)) - } -} -impl From for AppsError { - fn from(err: serde_json::Error) -> Self { - AppsError::SerdeJson(err) - } -} -impl From for AppsError { - fn from(err: UserAccountError) -> Self { - AppsError::UserAccount(err) - } -} -pub type AppsResult = Result; +mod result; +pub mod session; +pub use result::*; pub struct AppDao { //内部依赖 diff --git a/server/lsys-app/src/dao/result.rs b/server/lsys-app/src/dao/result.rs new file mode 100644 index 0000000..d57d8dc --- /dev/null +++ b/server/lsys-app/src/dao/result.rs @@ -0,0 +1,84 @@ +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage}; +use std::{ + // error::Error, + // fmt::{Display, Formatter}, + time::SystemTimeError, +}; + +use deadpool_redis::PoolError; + +use lsys_user::dao::account::UserAccountError; + +use redis::RedisError; + +#[derive(Debug)] +pub enum AppsError { + Sqlx(sqlx::Error), + System(FluentMessage), + Redis(RedisError), + RedisPool(PoolError), + ScopeNotFind(FluentMessage), + UserAccount(UserAccountError), + SerdeJson(serde_json::Error), +} + +impl IntoFluentMessage for AppsError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + AppsError::System(e) => e.to_owned(), + AppsError::ScopeNotFind(e) => e.to_owned(), + AppsError::Sqlx(e) => { + fluent_message!("sqlx-error", e) + } + AppsError::Redis(e) => { + fluent_message!("redis-error", e) + } + AppsError::RedisPool(e) => { + fluent_message!("redis-error", e) + } + AppsError::UserAccount(e) => e.to_fluent_message(), + AppsError::SerdeJson(e) => { + fluent_message!("serde-json-error", e) + } + } + } +} + +// impl Display for AppsError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } + +impl From for AppsError { + fn from(err: sqlx::Error) -> Self { + AppsError::Sqlx(err) + } +} +impl From for AppsError { + fn from(err: RedisError) -> Self { + AppsError::Redis(err) + } +} +impl From for AppsError { + fn from(err: PoolError) -> Self { + AppsError::RedisPool(err) + } +} +impl From for AppsError { + fn from(err: SystemTimeError) -> Self { + AppsError::System(fluent_message!("time-error", err)) + } +} +impl From for AppsError { + fn from(err: serde_json::Error) -> Self { + AppsError::SerdeJson(err) + } +} +impl From for AppsError { + fn from(err: UserAccountError) -> Self { + AppsError::UserAccount(err) + } +} + +pub type AppsResult = Result; diff --git a/server/lsys-app/src/dao/session.rs b/server/lsys-app/src/dao/session.rs index 0aee901..edc99a5 100644 --- a/server/lsys-app/src/dao/session.rs +++ b/server/lsys-app/src/dao/session.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use async_trait::async_trait; -use lsys_core::fluent_message; +use lsys_core::{fluent_message, IntoFluentMessage}; use lsys_user::dao::auth::{ SessionData, SessionToken, SessionTokenData, SessionUserData, UserAuthError, UserAuthResult, UserSession, @@ -90,8 +90,8 @@ impl UserSession for RestAuthSession { .await .map_err(|e| { UserAuthError::System(fluent_message!("user-session-get-error",{ - "client_id":token_data.client_id, - "msg":e + "client_id":&token_data.client_id, + "msg":e.to_fluent_message(), })) })?; Ok(data) @@ -106,8 +106,8 @@ impl UserSession for RestAuthSession { .await .map_err(|e| { UserAuthError::System(fluent_message!("user-session-refresh-error",{ - "client_id":token_data.client_id, - "msg":e + "client_id":&token_data.client_id, + "msg":e.to_fluent_message() })) })?; let data = self @@ -117,8 +117,8 @@ impl UserSession for RestAuthSession { .await .map_err(|e| { UserAuthError::System(fluent_message!("user-session-refresh-error",{ - "client_id":token_data.client_id, - "msg":e + "client_id":&token_data.client_id, + "msg":e.to_fluent_message() })) })?; self.set_session_token(SessionToken::from(data.clone())); @@ -129,7 +129,12 @@ impl UserSession for RestAuthSession { .app_oauth .clear_session(&self.user_token) .await - .map_err(|e| UserAuthError::System(fluent_message!("user-session-clear-error", e)))?; + .map_err(|e| { + UserAuthError::System(fluent_message!( + "user-session-clear-error", + e.to_fluent_message() + )) + })?; Ok(()) } } diff --git a/server/lsys-core/src/app_core.rs b/server/lsys-core/src/app_core/mod.rs similarity index 83% rename from server/lsys-core/src/app_core.rs rename to server/lsys-core/src/app_core/mod.rs index 64cb816..08de02a 100644 --- a/server/lsys-core/src/app_core.rs +++ b/server/lsys-core/src/app_core/mod.rs @@ -1,14 +1,14 @@ +mod result; + // use config::Config; -use deadpool_redis::{Config as RedisConfig, CreatePoolError, Runtime}; +use deadpool_redis::{Config as RedisConfig, Runtime}; use dotenv::dotenv; use log::LevelFilter; -use redis::RedisError; + use sqlx::pool::PoolOptions; use sqlx::{ConnectOptions, Connection, Database, Pool}; -use std::env::{self, VarError}; -use std::error::Error; -use std::fmt::{Display, Formatter}; +use std::env; use std::str::FromStr; use std::path::{Path, PathBuf}; @@ -16,100 +16,14 @@ use tera::Tera; use sqlx_model::TableName; -use crate::{Config, ConfigError, FluentBundleError, RemoteNotifyError}; - -#[derive(Debug)] -pub enum AppCoreError { - Sqlx(sqlx::Error), - Env(VarError), - Tera(tera::Error), - Io(std::io::Error), - System(String), - Log(String), - Redis(RedisError), - RedisPool(CreatePoolError), - Dotenv(dotenv::Error), - AppDir(String), - Config(ConfigError), - Fluent(FluentBundleError), - RemoteNotify(RemoteNotifyError), -} - -impl Display for AppCoreError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl Error for AppCoreError {} -impl From for AppCoreError { - fn from(err: sqlx::Error) -> Self { - AppCoreError::Sqlx(err) - } -} -impl From for AppCoreError { - fn from(err: CreatePoolError) -> Self { - AppCoreError::RedisPool(err) - } -} -impl From for AppCoreError { - fn from(err: RemoteNotifyError) -> Self { - AppCoreError::RemoteNotify(err) - } -} - -impl From for AppCoreError { - fn from(err: VarError) -> Self { - AppCoreError::Env(err) - } -} -impl From for AppCoreError { - fn from(err: tera::Error) -> Self { - AppCoreError::Tera(err) - } -} -impl From for AppCoreError { - fn from(err: std::io::Error) -> Self { - AppCoreError::Io(err) - } -} -impl From for AppCoreError { - fn from(err: RedisError) -> Self { - AppCoreError::Redis(err) - } -} -impl From for AppCoreError { - fn from(err: dotenv::Error) -> Self { - AppCoreError::Dotenv(err) - } -} -// impl From for AppCoreError { -// fn from(err: core::convert::Infallible) -> Self { -// AppCoreError::AppDir(err.to_string()) -// } -// } -impl From for AppCoreError { - fn from(err: ConfigError) -> Self { - AppCoreError::Config(err) - } -} -impl From for AppCoreError { - fn from(err: config::ConfigError) -> Self { - AppCoreError::Config(ConfigError::Config(err)) - } -} -impl From for AppCoreError { - fn from(err: FluentBundleError) -> Self { - AppCoreError::Fluent(err) - } -} +use crate::{Config, ConfigError}; +pub use result::*; pub struct AppCore { pub app_path: PathBuf, pub config: Config, } -pub type AppCoreResult = Result; - impl AppCore { pub async fn init( app_dir: &str, diff --git a/server/lsys-core/src/app_core/result.rs b/server/lsys-core/src/app_core/result.rs new file mode 100644 index 0000000..c9f4faf --- /dev/null +++ b/server/lsys-core/src/app_core/result.rs @@ -0,0 +1,117 @@ +// use config::Config; +use deadpool_redis::CreatePoolError; + +use redis::RedisError; + +use std::env::VarError; +// use std::error::Error; +// use std::fmt::{Display, Formatter}; + +use crate::{fluent_message, AppCore, FluentBundleError, FluentMessage, RemoteNotifyError}; +use crate::{ConfigError, IntoFluentMessage}; +#[derive(Debug)] +pub enum AppCoreError { + Sqlx(sqlx::Error), + Env(VarError), + Tera(tera::Error), + Io(std::io::Error), + System(String), + Log(String), + Redis(RedisError), + RedisPool(CreatePoolError), + Dotenv(dotenv::Error), + AppDir(String), + Config(ConfigError), + Fluent(FluentBundleError), + RemoteNotify(RemoteNotifyError), +} + +impl IntoFluentMessage for AppCoreError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + AppCoreError::Sqlx(err) => fluent_message!("sqlx-error", err), + AppCoreError::Env(err) => fluent_message!("env-error", err), + AppCoreError::Tera(err) => fluent_message!("tera-error", err), + AppCoreError::Io(err) => fluent_message!("file-error", err), + AppCoreError::System(err) => fluent_message!("app-error", err), + AppCoreError::Log(err) => fluent_message!("log-error", err), + AppCoreError::Redis(err) => fluent_message!("redis-error", err), + AppCoreError::RedisPool(err) => fluent_message!("redis-error", err), + AppCoreError::Dotenv(err) => fluent_message!("env-error", err), + AppCoreError::AppDir(err) => fluent_message!("file-error", err), + AppCoreError::Config(err) => err.to_fluent_message(), + AppCoreError::RemoteNotify(err) => err.to_fluent_message(), + AppCoreError::Fluent(err) => err.to_fluent_message(), + } + } +} + +// impl Display for AppCoreError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +// impl Error for AppCoreError {} +impl From for AppCoreError { + fn from(err: sqlx::Error) -> Self { + AppCoreError::Sqlx(err) + } +} +impl From for AppCoreError { + fn from(err: CreatePoolError) -> Self { + AppCoreError::RedisPool(err) + } +} +impl From for AppCoreError { + fn from(err: RemoteNotifyError) -> Self { + AppCoreError::RemoteNotify(err) + } +} + +impl From for AppCoreError { + fn from(err: VarError) -> Self { + AppCoreError::Env(err) + } +} +impl From for AppCoreError { + fn from(err: tera::Error) -> Self { + AppCoreError::Tera(err) + } +} +impl From for AppCoreError { + fn from(err: std::io::Error) -> Self { + AppCoreError::Io(err) + } +} +impl From for AppCoreError { + fn from(err: RedisError) -> Self { + AppCoreError::Redis(err) + } +} +impl From for AppCoreError { + fn from(err: dotenv::Error) -> Self { + AppCoreError::Dotenv(err) + } +} +// impl From for AppCoreError { +// fn from(err: core::convert::Infallible) -> Self { +// AppCoreError::AppDir(err.to_string()) +// } +// } +impl From for AppCoreError { + fn from(err: ConfigError) -> Self { + AppCoreError::Config(err) + } +} +impl From for AppCoreError { + fn from(err: config::ConfigError) -> Self { + AppCoreError::Config(ConfigError::Config(err)) + } +} +impl From for AppCoreError { + fn from(err: FluentBundleError) -> Self { + AppCoreError::Fluent(err) + } +} + +pub type AppCoreResult = Result; diff --git a/server/lsys-core/src/cache/mod.rs b/server/lsys-core/src/cache/mod.rs index 26c9329..e7230cd 100644 --- a/server/lsys-core/src/cache/mod.rs +++ b/server/lsys-core/src/cache/mod.rs @@ -15,7 +15,7 @@ use tracing::{debug, warn}; pub use clear::*; -use crate::{now_time, LocalExecType, RemoteNotify}; +use crate::{now_time, IntoFluentMessage, LocalExecType, RemoteNotify}; pub const REMOTE_NOTIFY_TYPE_CACHE: u8 = 101; @@ -158,7 +158,10 @@ where ) .await { - warn!("notify clear cache error:{}", err); + warn!( + "notify clear cache error:{}", + err.to_fluent_message().default_format() + ); } } } diff --git a/server/lsys-core/src/config.rs b/server/lsys-core/src/config/mod.rs similarity index 90% rename from server/lsys-core/src/config.rs rename to server/lsys-core/src/config/mod.rs index 0e23928..426af6b 100644 --- a/server/lsys-core/src/config.rs +++ b/server/lsys-core/src/config/mod.rs @@ -1,3 +1,6 @@ +mod result; +pub use result::*; + use std::{collections::HashMap, path::Path}; use config::builder::DefaultState; @@ -7,21 +10,6 @@ pub struct Config { configs: HashMap, } -#[derive(Debug)] -pub enum ConfigError { - Io(std::io::Error), - Config(config::ConfigError), -} -impl From for ConfigError { - fn from(err: std::io::Error) -> Self { - ConfigError::Io(err) - } -} -impl From for ConfigError { - fn from(err: config::ConfigError) -> Self { - ConfigError::Config(err) - } -} impl Config { fn default_config>( path: &P, diff --git a/server/lsys-core/src/config/result.rs b/server/lsys-core/src/config/result.rs new file mode 100644 index 0000000..f30dfd0 --- /dev/null +++ b/server/lsys-core/src/config/result.rs @@ -0,0 +1,28 @@ +use crate::{fluent_message, FluentMessage, IntoFluentMessage}; + +//config +#[derive(Debug)] +pub enum ConfigError { + Io(std::io::Error), + Config(config::ConfigError), +} + +impl IntoFluentMessage for ConfigError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + ConfigError::Io(err) => fluent_message!("file-error", err), + ConfigError::Config(err) => fluent_message!("config-error", err), + } + } +} + +impl From for ConfigError { + fn from(err: std::io::Error) -> Self { + ConfigError::Io(err) + } +} +impl From for ConfigError { + fn from(err: config::ConfigError) -> Self { + ConfigError::Config(err) + } +} diff --git a/server/lsys-core/src/fluents/bundle.rs b/server/lsys-core/src/fluents/bundle.rs index 22acf77..8149d7c 100644 --- a/server/lsys-core/src/fluents/bundle.rs +++ b/server/lsys-core/src/fluents/bundle.rs @@ -3,22 +3,10 @@ use intl_memoizer::concurrent::IntlLangMemoizer; use crate::FluentMessage; +use crate::FluentBundleError; use std::{collections::HashMap, path::Path, str::FromStr, sync::Arc}; use tokio::io::AsyncReadExt; use unic_langid::LanguageIdentifier; - -#[derive(Debug)] -pub enum FluentBundleError { - Io(std::io::Error), - System(String), -} - -impl From for FluentBundleError { - fn from(err: std::io::Error) -> Self { - FluentBundleError::Io(err) - } -} - pub struct FluentMgr { default_bundle: Arc, default_lang: &'static str, @@ -198,7 +186,11 @@ impl FluentBundle { msg.value().map(|pattern| { let mut args: fluent::FluentArgs = fluent::FluentArgs::new(); for (k, v) in &message.data { - args.set(k, v.as_str()); + let tmp = match v { + crate::FluentData::Message(fmsg) => self.format_message(fmsg), + crate::FluentData::String(msg) => msg.to_owned(), + }; + args.set(k, tmp); } let mut errors = vec![]; fluent @@ -207,6 +199,12 @@ impl FluentBundle { }) }) }) - .unwrap_or_else(|| message.to_string()) + .unwrap_or_else(|| { + if message.data.is_empty() { + message.id.to_string() + } else { + message.default_format() + } + }) } } diff --git a/server/lsys-core/src/fluents/message.rs b/server/lsys-core/src/fluents/message.rs index fadab6a..6a18837 100644 --- a/server/lsys-core/src/fluents/message.rs +++ b/server/lsys-core/src/fluents/message.rs @@ -1,20 +1,60 @@ -#[derive(Debug)] +#[derive(Debug, Clone)] +pub enum FluentData { + Message(FluentMessage), + String(String), +} +impl From for FluentData { + fn from(value: FluentMessage) -> Self { + FluentData::Message(value) + } +} +impl From for FluentData { + fn from(value: T) -> Self { + FluentData::String(value.to_string()) + } +} + +#[derive(Debug, Clone)] pub struct FluentMessage { pub id: String, pub crate_name: String, - pub data: Vec<(String, String)>, + pub data: Vec<(String, FluentData)>, } -impl std::fmt::Display for FluentMessage { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl FluentMessage { + pub fn default_format(&self) -> String { if self.data.is_empty() { - write!(f, "{}", self.id) + self.id.to_owned() } else { - write!(f, "{}:{}", self.id, serde_json::json!(self.data)) + let data = self + .data + .iter() + .map(|e| { + format!( + "{}:{}", + e.0, + match &e.1 { + FluentData::Message(e1) => e1.default_format(), + FluentData::String(e1) => e1.to_owned(), + } + ) + }) + .collect::>(); + format!("{}:{}", self.id, serde_json::json!(data)) } } } +pub trait IntoFluentMessage { + fn to_fluent_message(&self) -> FluentMessage; +} + +impl IntoFluentMessage for FluentMessage { + fn to_fluent_message(&self) -> FluentMessage { + self.to_owned() + } +} + #[macro_export] macro_rules! fluent_message { ($key:literal) => { @@ -32,7 +72,7 @@ macro_rules! fluent_message { id: $key.to_owned(), crate_name:env!("CARGO_PKG_NAME").to_string(), data:vec![ - $( ($msg_key.to_owned(), $msg_val.to_string()) ),* + $( ($msg_key.to_owned(),$crate::FluentData::from($msg_val)) ),* ] } } @@ -42,24 +82,24 @@ macro_rules! fluent_message { $crate::FluentMessage { id: $key.to_owned(), crate_name:env!("CARGO_PKG_NAME").to_string(), - data:vec![("msg".to_owned(),$msg_val.to_string())] + data:vec![("msg".to_owned(),$crate::FluentData::from($msg_val))] } } }; } -impl From for FluentMessage { - fn from(value: String) -> Self { - fluent_message!("app-error", value) - } -} -impl From<&String> for FluentMessage { - fn from(value: &String) -> Self { - fluent_message!("app-error", value) - } -} -impl From<&str> for FluentMessage { - fn from(value: &str) -> Self { - fluent_message!("app-error", value) - } -} +// impl From for FluentMessage { +// fn from(value: String) -> Self { +// fluent_message!("app-error", value) +// } +// } +// impl From<&String> for FluentMessage { +// fn from(value: &String) -> Self { +// fluent_message!("app-error", value) +// } +// } +// impl From<&str> for FluentMessage { +// fn from(value: &str) -> Self { +// fluent_message!("app-error", value) +// } +// } diff --git a/server/lsys-core/src/fluents/mod.rs b/server/lsys-core/src/fluents/mod.rs index 290b8ad..1a1c0b5 100644 --- a/server/lsys-core/src/fluents/mod.rs +++ b/server/lsys-core/src/fluents/mod.rs @@ -3,3 +3,5 @@ mod message; pub use bundle::*; pub use message::*; +mod result; +pub use result::*; diff --git a/server/lsys-core/src/fluents/result.rs b/server/lsys-core/src/fluents/result.rs new file mode 100644 index 0000000..937c910 --- /dev/null +++ b/server/lsys-core/src/fluents/result.rs @@ -0,0 +1,21 @@ +use crate::{fluent_message, FluentMessage, IntoFluentMessage}; + +#[derive(Debug)] +pub enum FluentBundleError { + Io(std::io::Error), + System(String), +} +impl IntoFluentMessage for FluentBundleError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + FluentBundleError::Io(err) => fluent_message!("fluent-file-error", err), + FluentBundleError::System(err) => fluent_message!("fluent-error", err), + } + } +} + +impl From for FluentBundleError { + fn from(err: std::io::Error) -> Self { + FluentBundleError::Io(err) + } +} diff --git a/server/lsys-core/src/listen_notify.rs b/server/lsys-core/src/listen_notify/mod.rs similarity index 93% rename from server/lsys-core/src/listen_notify.rs rename to server/lsys-core/src/listen_notify/mod.rs index 65effb0..829643b 100644 --- a/server/lsys-core/src/listen_notify.rs +++ b/server/lsys-core/src/listen_notify/mod.rs @@ -1,7 +1,6 @@ -use std::fmt::{Debug, Display, Formatter}; +use std::fmt::Debug; use std::sync::Arc; -use deadpool_redis::PoolError; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -12,24 +11,9 @@ use tokio::time::{sleep, Duration}; use redis::AsyncCommands; use tracing::{debug, error, info, warn}; -use crate::{fluent_message, AppCore, FluentMessage}; - -#[derive(Debug)] -pub enum WaitNotifyError { - System(FluentMessage), - Redis(redis::RedisError), - RedisPool(PoolError), - TimeOut, -} - -impl Display for WaitNotifyError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -pub type WaitNotifyResult = Result; - +use crate::{fluent_message, AppCore, IntoFluentMessage}; +mod result; +pub use result::*; pub trait WaitItem { fn eq(&self, other: &Self) -> bool; } @@ -122,7 +106,6 @@ impl WaitNotify { let con_res = redis_client.get_async_connection().await; match con_res { Ok(mut redis) => { - debug!("notify is connect"); let channel_name = self.redis_channel_name( hostname::get() .unwrap_or_default() @@ -167,7 +150,10 @@ impl WaitNotify { } } Err(err) => { - warn!("create remote notify listen client fail:{}", err); + warn!( + "create remote notify listen client fail:{}", + err.to_fluent_message().default_format() + ); tokio::time::sleep(Duration::from_secs(1)).await; } } diff --git a/server/lsys-core/src/listen_notify/result.rs b/server/lsys-core/src/listen_notify/result.rs new file mode 100644 index 0000000..0994c82 --- /dev/null +++ b/server/lsys-core/src/listen_notify/result.rs @@ -0,0 +1,30 @@ +use crate::{fluent_message, FluentMessage, IntoFluentMessage}; +use deadpool_redis::PoolError; +use std::fmt::Debug; + +#[derive(Debug)] +pub enum WaitNotifyError { + System(FluentMessage), + Redis(redis::RedisError), + RedisPool(PoolError), + TimeOut, +} + +impl IntoFluentMessage for WaitNotifyError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + WaitNotifyError::System(err) => err.to_owned(), + WaitNotifyError::Redis(err) => fluent_message!("redis-error", err), + WaitNotifyError::RedisPool(err) => fluent_message!("redis-error", err), + WaitNotifyError::TimeOut => fluent_message!("wait-notify-timeout"), + } + } +} + +// impl Display for WaitNotifyError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } + +pub type WaitNotifyResult = Result; diff --git a/server/lsys-core/src/remote_notify/mod.rs b/server/lsys-core/src/remote_notify/mod.rs index b0eed11..2548834 100644 --- a/server/lsys-core/src/remote_notify/mod.rs +++ b/server/lsys-core/src/remote_notify/mod.rs @@ -1,10 +1,10 @@ use std::collections::HashMap; -use std::error::Error; -use std::fmt::{Display, Formatter}; +// use std::error::Error; + use std::sync::Arc; use async_trait::async_trait; -use deadpool_redis::PoolError; + use serde::{Deserialize, Serialize}; use serde_json::Value; use snowflake::SnowflakeIdGenerator; @@ -13,36 +13,13 @@ use tokio::time::Duration; use futures_util::StreamExt; -use redis::{AsyncCommands, RedisError}; use tracing::{debug, error, info, warn}; use crate::AppCore; - -#[derive(Debug)] -pub enum RemoteNotifyError { - System(String), - RedisPool(PoolError), - Redis(RedisError), - RemoteTimeOut, -} - -impl Display for RemoteNotifyError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl Error for RemoteNotifyError {} -impl From for RemoteNotifyError { - fn from(err: RedisError) -> Self { - RemoteNotifyError::Redis(err) - } -} -impl From for RemoteNotifyError { - fn from(err: PoolError) -> Self { - RemoteNotifyError::RedisPool(err) - } -} - +mod result; +pub use result::*; +use crate::IntoFluentMessage; +use redis::AsyncCommands as _; //发送消息 #[derive(Serialize, Deserialize, Clone)] pub struct MsgSendBody { @@ -384,7 +361,7 @@ impl RemoteNotify { } } Err(err) => { - warn!("create remote notify listen client fail:{}", err); + warn!("create remote notify listen client fail:{}", err.to_fluent_message().default_format()); tokio::time::sleep(Duration::from_secs(1)).await; } } diff --git a/server/lsys-core/src/remote_notify/result.rs b/server/lsys-core/src/remote_notify/result.rs new file mode 100644 index 0000000..9466266 --- /dev/null +++ b/server/lsys-core/src/remote_notify/result.rs @@ -0,0 +1,44 @@ +// use std::error::Error; +// use std::fmt::{Display, Formatter}; + +use deadpool_redis::PoolError; + +use redis::RedisError; + +use crate::{fluent_message, FluentMessage, IntoFluentMessage}; + +#[derive(Debug)] +pub enum RemoteNotifyError { + System(String), + RedisPool(PoolError), + Redis(RedisError), + RemoteTimeOut, +} + +impl IntoFluentMessage for RemoteNotifyError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + RemoteNotifyError::System(err) => fluent_message!("notify-error", err), + RemoteNotifyError::RedisPool(err) => fluent_message!("redis-error", err), + RemoteNotifyError::Redis(err) => fluent_message!("redis-error", err), + RemoteNotifyError::RemoteTimeOut => fluent_message!("notify-time-out"), + } + } +} + +// impl Display for RemoteNotifyError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +// impl Error for RemoteNotifyError {} +impl From for RemoteNotifyError { + fn from(err: RedisError) -> Self { + RemoteNotifyError::Redis(err) + } +} +impl From for RemoteNotifyError { + fn from(err: PoolError) -> Self { + RemoteNotifyError::RedisPool(err) + } +} diff --git a/server/lsys-core/src/task/task_executor.rs b/server/lsys-core/src/task/task_executor.rs index fb164b8..8e8717b 100644 --- a/server/lsys-core/src/task/task_executor.rs +++ b/server/lsys-core/src/task/task_executor.rs @@ -18,7 +18,7 @@ use tokio::task::{AbortHandle, JoinSet}; use tokio::time::sleep; use tracing::{debug, error, info, warn}; -use crate::{now_time, AppCore}; +use crate::{now_time, AppCore, IntoFluentMessage}; //最外层的发送任务派发封装 //不包含具体的发送逻辑 @@ -280,7 +280,10 @@ impl< let redis_client = match app_core.create_redis_client() { Ok(redis_client) => redis_client, Err(err) => { - error!("create redis fail:{}", err); + error!( + "create redis fail:{}", + err.to_fluent_message().default_format() + ); return; } }; diff --git a/server/lsys-core/src/utils/time.rs b/server/lsys-core/src/utils/time.rs index 5323f1b..6e6b0a7 100644 --- a/server/lsys-core/src/utils/time.rs +++ b/server/lsys-core/src/utils/time.rs @@ -1,18 +1,20 @@ use chrono::offset::Local; use chrono::{DateTime, FixedOffset, NaiveDateTime, TimeZone}; use std::time::{SystemTime, SystemTimeError}; + +use crate::{fluent_message, FluentMessage}; pub fn now_time() -> Result { Ok(SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH)? .as_secs()) } -pub fn str_time(str_time: &str) -> Result, String> { - let dt = - NaiveDateTime::parse_from_str(str_time, "%Y-%m-%d %H:%M:%S").map_err(|e| e.to_string())?; +pub fn str_time(str_time: &str) -> Result, FluentMessage> { + let dt = NaiveDateTime::parse_from_str(str_time, "%Y-%m-%d %H:%M:%S") + .map_err(|err| fluent_message!("time-format-error", err))?; let ze = Local::now().timezone().offset_from_utc_datetime(&dt); match dt.and_local_timezone(ze) { chrono::LocalResult::Single(t) => Ok(t), - _ => Err("parse time fail,on add zone".to_string()), + _ => Err(fluent_message!("time-zone-error")), } } diff --git a/server/lsys-core/src/valid_code/mod.rs b/server/lsys-core/src/valid_code/mod.rs index d312f89..494910e 100644 --- a/server/lsys-core/src/valid_code/mod.rs +++ b/server/lsys-core/src/valid_code/mod.rs @@ -1,13 +1,13 @@ -use std::{ - fmt::{Display, Formatter}, - string::FromUtf8Error, -}; + use async_trait::async_trait; -use deadpool_redis::{redis::AsyncCommands, Connection, PoolError}; -use redis::RedisError; +use deadpool_redis::{redis::AsyncCommands, Connection}; + -use crate::{fluent_message, rand_str, FluentMessage, RandType}; +mod result; +pub use result::*; + +use crate::{fluent_message, rand_str, RandType}; const CODE_SAVE_KEY: &str = "valid-save"; pub struct ValidCode { @@ -15,42 +15,6 @@ pub struct ValidCode { ignore_case: bool, redis: deadpool_redis::Pool, } -#[derive(Debug)] -//不匹配错误 -pub struct ValidCodeCheckError { - pub message: FluentMessage, - pub prefix: String, -} -#[derive(Debug)] -pub enum ValidCodeError { - Utf8Err(FluentMessage), - Redis(RedisError), - RedisPool(PoolError), - Tag(FluentMessage), - DelayTimeout(ValidCodeCheckError), - NotMatch(ValidCodeCheckError), -} -impl Display for ValidCodeError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl From for ValidCodeError { - fn from(err: FromUtf8Error) -> Self { - ValidCodeError::Utf8Err(fluent_message!("utf-error", err)) - } -} -impl From for ValidCodeError { - fn from(err: RedisError) -> Self { - ValidCodeError::Redis(err) - } -} -impl From for ValidCodeError { - fn from(err: PoolError) -> Self { - ValidCodeError::RedisPool(err) - } -} - #[async_trait] pub trait ValidCodeData { async fn get_code<'t>( diff --git a/server/lsys-core/src/valid_code/result.rs b/server/lsys-core/src/valid_code/result.rs new file mode 100644 index 0000000..adcf440 --- /dev/null +++ b/server/lsys-core/src/valid_code/result.rs @@ -0,0 +1,58 @@ +use std::{ + // fmt::{Display, Formatter}, + string::FromUtf8Error, +}; + +use deadpool_redis::PoolError; +use redis::RedisError; + +use crate::{fluent_message, FluentMessage, IntoFluentMessage}; +#[derive(Debug)] +//不匹配错误 +pub struct ValidCodeCheckError { + pub message: FluentMessage, + pub prefix: String, +} +#[derive(Debug)] +pub enum ValidCodeError { + Utf8Err(FromUtf8Error), + Redis(RedisError), + RedisPool(PoolError), + Tag(FluentMessage), + DelayTimeout(ValidCodeCheckError), + NotMatch(ValidCodeCheckError), +} + +impl IntoFluentMessage for ValidCodeError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + ValidCodeError::Utf8Err(err) => fluent_message!("utf-parse-error", err), + ValidCodeError::Redis(err) => fluent_message!("redis-error", err), + ValidCodeError::RedisPool(err) => fluent_message!("redis-error", err), + ValidCodeError::Tag(err) => err.to_owned(), + ValidCodeError::DelayTimeout(err) => err.message.clone(), + ValidCodeError::NotMatch(err) => err.message.clone(), + } + } +} + +// impl Display for ValidCodeError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +impl From for ValidCodeError { + fn from(err: FromUtf8Error) -> Self { + ValidCodeError::Utf8Err(err) + } +} +impl From for ValidCodeError { + fn from(err: RedisError) -> Self { + ValidCodeError::Redis(err) + } +} +impl From for ValidCodeError { + fn from(err: PoolError) -> Self { + ValidCodeError::RedisPool(err) + } +} diff --git a/server/lsys-docs/src/dao/docs.rs b/server/lsys-docs/src/dao/docs.rs index 0dcd0dc..07967b3 100644 --- a/server/lsys-docs/src/dao/docs.rs +++ b/server/lsys-docs/src/dao/docs.rs @@ -14,7 +14,7 @@ use crate::{ DocLogsModelRef, DocMenuModel, DocMenuModelRef, DocMenuStatus, }, }; -use lsys_core::{fluent_message, now_time, PageParam, RequestEnv}; +use lsys_core::{fluent_message, now_time, IntoFluentMessage, PageParam, RequestEnv}; use serde::{Deserialize, Serialize}; use sqlx::{MySql, Pool}; use sqlx_model::{ @@ -291,9 +291,9 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-version-not-find", { - "url":param.url, - "tag": tmp.tag, - "version":tmp.build_version, + "url":¶m.url, + "tag": &tmp.tag, + "version":&tmp.build_version, } ), // format!( // "can't update url to {} ,version not find:{} [{}]", @@ -439,7 +439,7 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-submit-version-error", { - "version":param.build_version, + "version":¶m.build_version, } ), )); @@ -454,9 +454,9 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-version-not-find", { - "version":param.build_version, - "url": doc_git.url, - "tag":param.tag, + "version":¶m.build_version, + "url": &doc_git.url, + "tag":¶m.tag, } ), )); @@ -466,7 +466,7 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-tag-empty", { - "tag":param.tag, + "tag":¶m.tag, } ), )); @@ -577,7 +577,10 @@ impl GitDocs { .remote_delete_clone(&git_clone.id, &git_clone.host, timeout) .await { - info!("tag clone del fail:{}", err) + info!( + "tag clone del fail:{}", + err.to_fluent_message().default_format() + ) }; let rgit_clone = Select::type_new::() .reload(git_clone, &self.db) @@ -652,7 +655,7 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-status-wrong",{ "id":git_tag.id, - "tag":git_tag.tag, + "tag":&git_tag.tag, } ), )); @@ -663,7 +666,7 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-menu-empty",{ "id":git_tag.id, - "tag":git_tag.tag, + "tag":&git_tag.tag, } ), )); @@ -882,8 +885,8 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-menu-empty",{ "id":tag.id, - "tag":tag.tag, - "host_name":host_name + "tag":&tag.tag, + "host_name":&host_name } ), // format!( // "tag {} [{}] is clone not yet on:{}", @@ -899,9 +902,9 @@ impl GitDocs { if !prefix.is_empty() && !file_path.starts_with(&safe_path) { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-dir-access",{ - "prefix":prefix, - "tag":tag.tag, - "host_name":host_name + "prefix":&prefix, + "tag":&tag.tag, + "host_name":&host_name } ), )); @@ -958,8 +961,8 @@ impl GitDocs { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-menu-read-not-yet",{ "id":tag.id, - "tag":tag.tag, - "host_name":host_name + "tag":&tag.tag, + "host_name":&host_name } ), // format!( // "tag {} [{}] is clone not yet on:{}", @@ -1041,7 +1044,7 @@ impl GitDocs { // format!("your sumbit path,can't read data:{}", e) GitDocError::System(fluent_message!("doc-git-menu-file-error",{ "msg":e, - "tag":tag.tag, + "tag":&tag.tag, "file_path":menu_file.file_path.to_string_lossy() } )) @@ -1051,15 +1054,15 @@ impl GitDocs { if dat_str.trim().is_empty() || dat_str.trim() == "{}" { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-menu-file-empty",{ - "tag":tag.tag, - "file_path":menu_file.file_path.to_string_lossy() + "tag":&tag.tag, + "file_path":&menu_file.file_path.to_string_lossy() }), // "can't add empty menu".to_string(), )); } if let Err(err) = serde_json::from_slice::(&dat_u8) { return Err(crate::dao::GitDocError::System( fluent_message!("doc-git-menu-file-parse-error",{ - "tag":tag.tag, + "tag":&tag.tag, "file_path":menu_file.file_path.to_string_lossy(), "msg":err } @@ -1086,7 +1089,7 @@ impl GitDocs { return Err(GitDocError::System( fluent_message!("doc-git-menu-path-isfind",{ "menu_path":id.menu_path, - "tag":tag.tag, + "tag":&tag.tag, } ), )); diff --git a/server/lsys-docs/src/dao/mod.rs b/server/lsys-docs/src/dao/mod.rs index 4ba4ee2..388fac4 100644 --- a/server/lsys-docs/src/dao/mod.rs +++ b/server/lsys-docs/src/dao/mod.rs @@ -1,7 +1,6 @@ use std::env; -use std::error::Error; -use std::fmt::Display; -use std::fmt::Formatter; +// use std::error::Error; + use std::path::Path; use std::path::PathBuf; use std::sync::Arc; @@ -12,7 +11,6 @@ mod logger; mod task; pub use docs::*; -use lsys_core::FluentMessage; use lsys_core::RemoteNotify; use lsys_logger::dao::ChangeLogger; use relative_path::RelativePath; @@ -20,33 +18,8 @@ pub use task::*; use sqlx::MySql; use sqlx::Pool; - -#[derive(Debug)] -pub enum GitDocError { - Sqlx(sqlx::Error), - Git(git2::Error), - System(FluentMessage), - Remote(FluentMessage), -} -impl Display for GitDocError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl Error for GitDocError {} -impl From for GitDocError { - fn from(err: git2::Error) -> Self { - GitDocError::Git(err) - } -} -impl From for GitDocError { - fn from(err: sqlx::Error) -> Self { - GitDocError::Sqlx(err) - } -} - -pub type GitDocResult = Result; +mod result; +pub use result::*; pub struct DocsDao { //内部依赖 diff --git a/server/lsys-docs/src/dao/result.rs b/server/lsys-docs/src/dao/result.rs new file mode 100644 index 0000000..1ef03e7 --- /dev/null +++ b/server/lsys-docs/src/dao/result.rs @@ -0,0 +1,52 @@ +// use std::error::Error; +// use std::fmt::Display; +// use std::fmt::Formatter; + +use lsys_core::fluent_message; +use lsys_core::FluentMessage; +use lsys_core::IntoFluentMessage; + +#[derive(Debug)] +pub enum GitDocError { + Sqlx(sqlx::Error), + Git(git2::Error), + System(FluentMessage), + Remote(FluentMessage), +} + +impl IntoFluentMessage for GitDocError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + GitDocError::Sqlx(e) => fluent_message!("sqlx-error", e), + GitDocError::Git(e) => fluent_message!("git-error", e), + GitDocError::System(e) => e.to_owned(), + GitDocError::Remote(e) => e.to_owned(), + } + } +} + +// impl Display for GitDocError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } + +// impl Error for GitDocError {} +impl From for GitDocError { + fn from(err: git2::Error) -> Self { + GitDocError::Git(err) + } +} +impl From for GitDocError { + fn from(err: sqlx::Error) -> Self { + GitDocError::Sqlx(err) + } +} + +pub type GitDocResult = Result; + +pub(crate) enum CloneError { + VerNotMatch(String), + Err(String), +} +pub(crate) type CloneResult = Result<(), CloneError>; diff --git a/server/lsys-docs/src/dao/task.rs b/server/lsys-docs/src/dao/task.rs index 7d19b48..e799ff5 100644 --- a/server/lsys-docs/src/dao/task.rs +++ b/server/lsys-docs/src/dao/task.rs @@ -1,5 +1,6 @@ use lsys_core::{ - fluent_message, now_time, LocalExecType, MsgSendBody, RemoteNotify, RemoteTask, ReplyWait, + fluent_message, now_time, IntoFluentMessage, LocalExecType, MsgSendBody, RemoteNotify, + RemoteTask, ReplyWait, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -29,12 +30,8 @@ use crate::{ use sqlx_model::SqlQuote; use std::{env, format, path::Path, sync::Arc, time::Duration}; -use super::{git::git_download, GitDocResult}; -pub enum CloneError { - VerNotMatch(String), - Err(String), -} -type CloneResult = Result<(), CloneError>; +use super::{git::git_download, CloneError, CloneResult, GitDocResult}; + type TaskResult = (DocGitModel, DocGitTagModel, u64, CloneResult); //git model,tag model,clone id,clone result type TaskIngData = (u64, u64, AbortHandle); //tag id ,clone id,abort hand @@ -350,7 +347,11 @@ impl GitTask { let save_dir = match git_doc_path(save_dir, &clone_id, &None).await { Ok(set) => set, Err(err) => { - warn!("{} doc save file dir :{}", clone_id, err); + warn!( + "{} doc save file dir :{}", + clone_id, + err.to_fluent_message().default_format() + ); return false; } }; @@ -652,7 +653,10 @@ impl GitTask { ) .await { - warn!("notify clone fail:{}", err) + warn!( + "notify clone fail:{}", + err.to_fluent_message().default_format() + ) } } pub async fn remote_delete_clone( @@ -677,10 +681,13 @@ impl GitTask { ) .await { - warn!("remote delete clone fail:{}", err); + warn!( + "remote delete clone fail:{}", + err.to_fluent_message().default_format() + ); return Err(GitDocError::Remote(fluent_message!( "doc-notify-call-fail", - err + err.to_fluent_message() ))); } Ok(()) @@ -692,7 +699,11 @@ impl GitTask { let save_path = match git_doc_path(save_dir, clone_id, &None).await { Ok(set) => set, Err(err) => { - warn!("{} doc save file dir :{}", clone_id, err); + warn!( + "{} doc save file dir :{}", + clone_id, + err.to_fluent_message().default_format() + ); return; } }; @@ -755,17 +766,24 @@ impl RemoteTask for GitRemoteTask { DocAction::Del { clone_id } => match self.task.delete_clone(&clone_id).await { Ok(_) => { if let Err(err) = self.task.notify() { - warn!("delete clone after notify clone fail:{}", err); + warn!( + "delete clone after notify clone fail:{}", + err.to_fluent_message().default_format() + ); } } Err(err) => { - warn!("delete clone fail:{}", err); - return Err(err.to_string()); + let err_str = err.to_fluent_message().default_format(); + warn!("delete clone fail:{}", err_str); + return Err(err_str); } }, DocAction::Clone => { if let Err(err) = self.task.notify() { - warn!("notify clone fail:{}", err); + warn!( + "notify clone fail:{}", + err.to_fluent_message().default_format() + ); } } } diff --git a/server/lsys-docs/src/lib.rs b/server/lsys-docs/src/lib.rs index b47535c..7daf44e 100644 --- a/server/lsys-docs/src/lib.rs +++ b/server/lsys-docs/src/lib.rs @@ -1,4 +1,4 @@ pub mod dao; pub mod model; -pub use git2::Error as gitError; +pub use git2::Error as GitError; diff --git a/server/lsys-logger/src/dao/mod.rs b/server/lsys-logger/src/dao/mod.rs index a7b74de..ee63ac0 100644 --- a/server/lsys-logger/src/dao/mod.rs +++ b/server/lsys-logger/src/dao/mod.rs @@ -1,27 +1,5 @@ -use std::{ - error::Error, - fmt::{Display, Formatter}, -}; mod change_log; pub use change_log::*; -#[derive(Debug)] -pub enum LoggerError { - Sqlx(sqlx::Error), - // System(FluentMessage), -} -impl Display for LoggerError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl Error for LoggerError {} - -impl From for LoggerError { - fn from(err: sqlx::Error) -> Self { - LoggerError::Sqlx(err) - } -} - -pub type LoggerResult = Result; +mod result; +pub use result::*; diff --git a/server/lsys-logger/src/dao/result.rs b/server/lsys-logger/src/dao/result.rs new file mode 100644 index 0000000..5d32569 --- /dev/null +++ b/server/lsys-logger/src/dao/result.rs @@ -0,0 +1,34 @@ +// use std::{ +// // error::Error, +// fmt::{Display, Formatter}, +// }; + +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage}; +#[derive(Debug)] +pub enum LoggerError { + Sqlx(sqlx::Error), + // System(FluentMessage), +} +// impl Display for LoggerError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } + +impl IntoFluentMessage for LoggerError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + LoggerError::Sqlx(e) => fluent_message!("sqlx-error", e), + } + } +} + +// impl Error for LoggerError {} + +impl From for LoggerError { + fn from(err: sqlx::Error) -> Self { + LoggerError::Sqlx(err) + } +} + +pub type LoggerResult = Result; diff --git a/server/lsys-notify/src/dao/mod.rs b/server/lsys-notify/src/dao/mod.rs index b4309e8..27bc1b5 100644 --- a/server/lsys-notify/src/dao/mod.rs +++ b/server/lsys-notify/src/dao/mod.rs @@ -5,3 +5,5 @@ mod record; pub use notify::*; pub use notify_task::*; pub use record::*; +mod result; +pub use result::*; diff --git a/server/lsys-notify/src/dao/notify.rs b/server/lsys-notify/src/dao/notify.rs index 00d0974..7813324 100644 --- a/server/lsys-notify/src/dao/notify.rs +++ b/server/lsys-notify/src/dao/notify.rs @@ -1,54 +1,20 @@ use std::{ - error::Error, - fmt::{Display, Formatter}, + // error::Error, sync::Arc, }; -use deadpool_redis::PoolError; + use lsys_app::dao::app::Apps; -use lsys_core::{AppCore, FluentMessage, TaskDispatch}; +use lsys_core::{AppCore, TaskDispatch}; use lsys_logger::dao::ChangeLogger; use sqlx::Pool; use tracing::warn; use super::{ - NotifyRecord, NotifyTask, NotifyTaskAcquisition, NotifyTaskItem, NOTIFY_MIN_DELAY_TIME, + NotifyRecord, NotifyResult, NotifyTask, NotifyTaskAcquisition, NotifyTaskItem, + NOTIFY_MIN_DELAY_TIME, }; -//公共结构定义 -#[derive(Debug)] -pub enum NotifyError { - Sqlx(sqlx::Error), - Redis(redis::RedisError), - RedisPool(PoolError), - System(FluentMessage), -} -impl Display for NotifyError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl Error for NotifyError {} - -impl From for NotifyError { - fn from(err: sqlx::Error) -> Self { - NotifyError::Sqlx(err) - } -} -impl From for NotifyError { - fn from(err: redis::RedisError) -> Self { - NotifyError::Redis(err) - } -} -impl From for NotifyError { - fn from(err: PoolError) -> Self { - NotifyError::RedisPool(err) - } -} - -pub type NotifyResult = Result; - const NOTIFY_REDIS_PREFIX: &str = "notify-task"; pub trait NotifyData { fn to_string(&self) -> String; diff --git a/server/lsys-notify/src/dao/notify_task.rs b/server/lsys-notify/src/dao/notify_task.rs index 69add42..b6df171 100644 --- a/server/lsys-notify/src/dao/notify_task.rs +++ b/server/lsys-notify/src/dao/notify_task.rs @@ -7,7 +7,9 @@ use lsys_app::dao::{app::Apps, AppsError}; use sqlx::{MySql, Pool}; -use lsys_core::{now_time, TaskAcquisition, TaskData, TaskExecutor, TaskItem, TaskRecord}; +use lsys_core::{ + now_time, IntoFluentMessage, TaskAcquisition, TaskData, TaskExecutor, TaskItem, TaskRecord, +}; use sqlx_model::{sql_format, ModelTableName, Select, SqlExpr}; use tracing::warn; @@ -291,14 +293,14 @@ impl TaskExecutor for NotifyTask { change_notify_error_status(&self.db, &val.0.id, &val.0.try_num, "miss app") .await; } - Err(err) => return Err(err.to_string()), + Err(err) => return Err(err.to_fluent_message().default_format()), }; } Err(NotifyError::Sqlx(sqlx::Error::RowNotFound)) => { change_notify_error_status(&self.db, &val.0.id, &val.0.try_num, "miss config") .await; } - Err(err) => return Err(err.to_string()), + Err(err) => return Err(err.to_fluent_message().default_format()), }; Ok(()) } diff --git a/server/lsys-notify/src/dao/result.rs b/server/lsys-notify/src/dao/result.rs new file mode 100644 index 0000000..86f9a36 --- /dev/null +++ b/server/lsys-notify/src/dao/result.rs @@ -0,0 +1,48 @@ +//公共结构定义 + +use deadpool_redis::PoolError; + +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage}; + +#[derive(Debug)] +pub enum NotifyError { + Sqlx(sqlx::Error), + Redis(redis::RedisError), + RedisPool(PoolError), + System(FluentMessage), +} +// impl Display for NotifyError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +impl IntoFluentMessage for NotifyError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + NotifyError::Sqlx(e) => fluent_message!("sqlx-error", e), + NotifyError::Redis(err) => fluent_message!("redis-error", err), + NotifyError::RedisPool(err) => fluent_message!("redis-error", err), + NotifyError::System(err) => err.to_owned(), + } + } +} + +// impl Error for NotifyError {} + +impl From for NotifyError { + fn from(err: sqlx::Error) -> Self { + NotifyError::Sqlx(err) + } +} +impl From for NotifyError { + fn from(err: redis::RedisError) -> Self { + NotifyError::Redis(err) + } +} +impl From for NotifyError { + fn from(err: PoolError) -> Self { + NotifyError::RedisPool(err) + } +} + +pub type NotifyResult = Result; diff --git a/server/lsys-rbac/src/dao/rbac/access.rs b/server/lsys-rbac/src/dao/rbac/access.rs index 5cbca6b..6566ece 100644 --- a/server/lsys-rbac/src/dao/rbac/access.rs +++ b/server/lsys-rbac/src/dao/rbac/access.rs @@ -517,7 +517,7 @@ impl RbacAccess { tmp.check_res.res.clone(), fluent_message!("rbac-access-check-res-empty",{ // "res_id":res.res.id, - "res":tmp.check_res.res, + "res":&tmp.check_res.res, "op":otmp, "user_id":tmp.check_res.user_id, "view_user_id":user_id @@ -537,7 +537,7 @@ impl RbacAccess { bad_tmp.push(( tmp.check_res.res.clone(), fluent_message!("rbac-access-check-res-empty",{ - "res":tmp.check_res.res, + "res":&tmp.check_res.res, "op":tmp_op, "user_id":tmp.check_res.user_id, "view_user":user_id @@ -602,10 +602,10 @@ impl RbacAccess { let mut access = ( false, fluent_message!("rbac-access-check-access",{ - "res":check_item.res.name, + "res":&check_item.res.name, "res_id":check_item.res.id, "user_id":check_item.res.user_id, - "res_op":res_op.op_key, + "res_op":&res_op.op_key, "view_user_id":user_id }), //"user[{$user_id}] not find access [{$res}:{$res_id}] on [{$res_op}]" ); @@ -629,10 +629,7 @@ impl RbacAccess { } } if !access.0 { - info!( - "user {} access deny res :{},msg:{}", - user_id, check_item.res.name, access.1 - ); + info!("user {} access deny res :{}", user_id, check_item.res.name); bad_tmp.push((check_item.res.name.clone(), access.1)); } } diff --git a/server/lsys-rbac/src/dao/rbac/cache.rs b/server/lsys-rbac/src/dao/rbac/cache.rs index 61e75b7..51d8af9 100644 --- a/server/lsys-rbac/src/dao/rbac/cache.rs +++ b/server/lsys-rbac/src/dao/rbac/cache.rs @@ -1,7 +1,10 @@ use std::{str::FromStr, sync::Arc}; use async_trait::async_trait; -use lsys_core::cache::{LocalCache, LocalCacheClearItem}; +use lsys_core::{ + cache::{LocalCache, LocalCacheClearItem}, + IntoFluentMessage, +}; use super::{Rbac, RbacResData, ResKey, RoleAccessRow, RoleDetailRow}; @@ -35,7 +38,10 @@ impl LocalCacheClearItem for RbacLocalCacheClear { match self { RbacLocalCacheClear::ResKey(cache) => { cache - .del(&ResKey::from_str(msg).map_err(|e| e.to_string())?) + .del( + &ResKey::from_str(msg) + .map_err(|e| e.to_fluent_message().default_format())?, + ) .await } RbacLocalCacheClear::RoleRelation(cache) => cache.del(&msg.to_string()).await, diff --git a/server/lsys-rbac/src/dao/rbac/logger.rs b/server/lsys-rbac/src/dao/rbac/logger.rs index dcd54b7..87da7dd 100644 --- a/server/lsys-rbac/src/dao/rbac/logger.rs +++ b/server/lsys-rbac/src/dao/rbac/logger.rs @@ -1,4 +1,4 @@ -use std::fmt::Display; +// use std::fmt::Display; use lsys_logger::dao::ChangeLogData; use serde::Serialize; @@ -94,18 +94,18 @@ pub(crate) enum LogRoleUserAction { Add, Del, } -impl Display for LogRoleUserAction { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}", - match self { - LogRoleUserAction::Add => "add", - LogRoleUserAction::Del => "del", - } - ) - } -} +// impl Display for LogRoleUserAction { +// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +// write!( +// f, +// "{}", +// match self { +// LogRoleUserAction::Add => "add", +// LogRoleUserAction::Del => "del", +// } +// ) +// } +// } #[derive(Serialize)] pub(crate) struct LogRoleUser { @@ -120,9 +120,13 @@ impl ChangeLogData for LogRoleUser { "rbac-role-user" } fn message(&self) -> String { + let action_str = match self.action { + LogRoleUserAction::Add => "add", + LogRoleUserAction::Del => "del", + }; format!( "{} {} :{} ", - self.action, + action_str, self.name, match self.action { LogRoleUserAction::Add => { diff --git a/server/lsys-rbac/src/dao/rbac/mod.rs b/server/lsys-rbac/src/dao/rbac/mod.rs index 9f0ecf5..8984a5a 100644 --- a/server/lsys-rbac/src/dao/rbac/mod.rs +++ b/server/lsys-rbac/src/dao/rbac/mod.rs @@ -1,5 +1,5 @@ -use std::error::Error; -use std::fmt::{Display, Formatter}; +// use std::error::Error; + use std::sync::Arc; #[macro_use] mod macros; @@ -10,7 +10,7 @@ pub use check::*; pub use data::*; use logger::*; use lsys_core::cache::{LocalCache, LocalCacheConfig}; -use lsys_core::{FluentMessage, RemoteNotify}; +use lsys_core::RemoteNotify; use lsys_logger::dao::ChangeLogger; pub use res::*; pub use role::*; @@ -24,34 +24,14 @@ mod data; mod res; // mod res_tpl; mod logger; +mod result; mod role; mod tags; +pub use result::*; pub const PRIORITY_MAX: i8 = 100; pub const PRIORITY_MIN: i8 = 0; -#[derive(Debug)] -pub enum UserRbacError { - NotLogin(FluentMessage), - Sqlx(sqlx::Error), - System(FluentMessage), - Check(Vec<(String, FluentMessage)>), -} -impl Display for UserRbacError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl Error for UserRbacError {} - -pub type UserRbacResult = Result; - -impl From for UserRbacError { - fn from(err: sqlx::Error) -> Self { - UserRbacError::Sqlx(err) - } -} - pub struct Rbac { pub res: Arc, pub role: Arc, diff --git a/server/lsys-rbac/src/dao/rbac/result.rs b/server/lsys-rbac/src/dao/rbac/result.rs new file mode 100644 index 0000000..1895013 --- /dev/null +++ b/server/lsys-rbac/src/dao/rbac/result.rs @@ -0,0 +1,45 @@ +// use std::error::Error; +// use std::fmt::{Display, Formatter}; + +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage}; + +#[derive(Debug)] +pub enum UserRbacError { + NotLogin(FluentMessage), + Sqlx(sqlx::Error), + System(FluentMessage), + Check(Vec<(String, FluentMessage)>), +} +// impl Display for UserRbacError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +// impl Error for UserRbacError {} + +impl IntoFluentMessage for UserRbacError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + UserRbacError::Sqlx(e) => fluent_message!("sqlx-error", e), + UserRbacError::NotLogin(err) => err.to_owned(), + UserRbacError::System(err) => err.to_owned(), + UserRbacError::Check(_) => { + fluent_message!("rbac-check-fail") + // let mut msg = fluent_message!("rbac-check-fail"); + // msg.data = err + // .into_iter() + // .map(|e| (e.0, FluentData::Message(e.1))) + // .collect::>(); + // msg + } + } + } +} + +pub type UserRbacResult = Result; + +impl From for UserRbacError { + fn from(err: sqlx::Error) -> Self { + UserRbacError::Sqlx(err) + } +} diff --git a/server/lsys-rbac/src/dao/rbac/role.rs b/server/lsys-rbac/src/dao/rbac/role.rs index 2ae3df9..00ad4c1 100644 --- a/server/lsys-rbac/src/dao/rbac/role.rs +++ b/server/lsys-rbac/src/dao/rbac/role.rs @@ -1145,7 +1145,7 @@ impl RbacRole { if !RbacRoleUserRange::User.eq(role.user_range) { return Err(UserRbacError::System( fluent_message!("rbac-res-op-user-wrong",{ - "name":role.name, + "name":&role.name, "role_id":role.id, "range":role.user_range }), //"role({$name})[range:{$range}] can't set user [{$role_id}]", @@ -1657,7 +1657,7 @@ impl RbacRole { if !RbacRoleResOpRange::AllowCustom.eq(role.res_op_range) { return Err(UserRbacError::System( fluent_message!("rbac-res-op-range-wrong",{ - "name":role.name, + "name":&role.name, "role_id":role.id, "range":role.res_op_range }), //"role({$name})[range:{$range}] can't set ops [{$role_id}]",[ @@ -1689,7 +1689,7 @@ impl RbacRole { return Err(UserRbacError::System( fluent_message!("rbac-role-miss-res",{ "id":tmp.res.id, - "name":tmp.res.name + "name":&tmp.res.name }), //"res {$id} does not exist, may be delete",[ )); } @@ -1699,7 +1699,7 @@ impl RbacRole { if role.user_id > 0 && tmp.user_id != role.user_id { return Err(UserRbacError::System( fluent_message!("rbac-role-bad-res-user",{ - "res":tmp.name, + "res":&tmp.name, "user_id":tmp.user_id }), //,"res[{$res}:{$user_id}] do not belong to you" )); @@ -1733,7 +1733,7 @@ impl RbacRole { return Err(UserRbacError::System( fluent_message!("rbac-role-wrong-res-op",{ "id":optmp.0.id, - "name":optmp.0.name, + "name":&optmp.0.name, "res_id":optmp.0.res_id, "p_res_id":tmp.res.id }), //"res op [{$id}:] res id not match [{$res_id}!={$p_res_id}] ", @@ -1744,7 +1744,7 @@ impl RbacRole { return Err(UserRbacError::System( fluent_message!("rbac-role-miss-res-op",{ "id":optmp.0.id, - "name":optmp.0.name + "name":&optmp.0.name }), //"res op {$id} does not exist, may be delete",[ )); } diff --git a/server/lsys-sender/README.MD b/server/lsys-sender/README.MD index 178134d..1c11eb2 100644 --- a/server/lsys-sender/README.MD +++ b/server/lsys-sender/README.MD @@ -1,7 +1,5 @@ ##### 信息发送模块 -> 功能实现中。。。。 - > 对短信 邮件等对外发送信息进行二次封装 > 目标及功能 @@ -56,69 +54,3 @@ run-task[$task_id]={time:'任务开始',host:'任务所在主机'}//发送中记 ``` - - - -//@TODO 接口层批量发送问题 -msg ->1:1-> task -> 执行容器 - - - -消息记录表 排除指定任务ID方式获取任务列表 - -SMS -> 读取任务[] -> 执行任务[] - - - - -获取任务记录,标记任务 ->执行容器->完成->删除任务标记 - -$端口组 = [ - 端口A:[ - MGS 多个TO 1000 - ] - 端口B:[ - MGS 多个TO 10 - ] -] - $POLL=[]; - let err=None; - - loop{ - main': - if $端口组.is_empty(){ - return 错误 - } - for $端口组{ - for ${ - 1. 获取数量,查询待发送结果,加ID入进行中,加入发送$POLL - } - ] - lable': - SELECT($POLL){ - 'DD':ok{ - //成功,更新状态 - //失败[完成],退出-->return - //失败[继续],into_iter().c..`移除$端口组内数据` - //移除ID进行中 - //写入日志 - if !$端口组.is_empty(){ - if 检测数据库记录,未发送完成{ - 回到 loop main' 继续添加 - } - }else{ - err=Some(失败[继续]) - } - continue 'lable - } - finish{ - break - } - } -} -if err.is_some(){ - //未完成,有错误, -} - - - diff --git a/server/lsys-sender/src/dao/adapter/mailer/sender_smtp.rs b/server/lsys-sender/src/dao/adapter/mailer/sender_smtp.rs index f5d2875..5734431 100644 --- a/server/lsys-sender/src/dao/adapter/mailer/sender_smtp.rs +++ b/server/lsys-sender/src/dao/adapter/mailer/sender_smtp.rs @@ -21,7 +21,7 @@ use lettre::{ }, AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor, }; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_logger::dao::ChangeLogger; use lsys_setting::{ dao::{ @@ -297,7 +297,10 @@ impl SenderTaskExecutor for SmtpSenderTask { debug!("msgid:{} config_id:{} ", val.mail.id, tpl_config.id,); let smtp_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to smtp setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to smtp setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let hand_id = format!("{}-{}", smtp_setting.host, smtp_setting.user); let mail_tpl_config = serde_json::from_str::(&tpl_config.config_data) @@ -354,7 +357,11 @@ impl SenderTaskExecutor for SmtpSenderTask { ) .await .map_err(|e| { - SenderExecError::Finish(format!("render subject fail [{}]: {}", hand_id, e)) + SenderExecError::Finish(format!( + "render subject fail [{}]: {}", + hand_id, + e.to_fluent_message().default_format() + )) })?; email_builder = email_builder.subject(subject); @@ -363,7 +370,11 @@ impl SenderTaskExecutor for SmtpSenderTask { .render(SenderType::Mailer, &mail_tpl_config.body_tpl_id, &context) .await .map_err(|e| { - SenderExecError::Finish(format!("render body fail[{}]: {}", hand_id, e)) + SenderExecError::Finish(format!( + "render body fail[{}]: {}", + hand_id, + e.to_fluent_message().default_format() + )) })?; let msg = email_builder diff --git a/server/lsys-sender/src/dao/adapter/smser/sender_aliyun.rs b/server/lsys-sender/src/dao/adapter/smser/sender_aliyun.rs index 3ee5270..fb99403 100644 --- a/server/lsys-sender/src/dao/adapter/smser/sender_aliyun.rs +++ b/server/lsys-sender/src/dao/adapter/smser/sender_aliyun.rs @@ -10,7 +10,7 @@ use crate::{ }; use async_trait::async_trait; use chrono::NaiveDateTime; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_lib_sms::{AliSms, SendDetailItem, SendError, SendNotifyError}; use lsys_setting::{ dao::{ @@ -264,7 +264,10 @@ impl SenderTaskExecutor for AliYunSenderTask { ) -> SenderTaskResult { let ali_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to aliyun setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to aliyun setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let ali_config = serde_json::from_str::(&tpl_config.config_data).map_err(|e| { @@ -392,7 +395,10 @@ impl crate::dao::SmsStatusTaskExecutor for AliYunSendStatus { ) -> Result, SenderExecError> { let ali_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to aliyun setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to aliyun setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let naive_date_time = NaiveDateTime::from_timestamp_opt(msg.send_time as i64, 0).unwrap_or_default(); diff --git a/server/lsys-sender/src/dao/adapter/smser/sender_cloopen.rs b/server/lsys-sender/src/dao/adapter/smser/sender_cloopen.rs index 72166c4..f5bece4 100644 --- a/server/lsys-sender/src/dao/adapter/smser/sender_cloopen.rs +++ b/server/lsys-sender/src/dao/adapter/smser/sender_cloopen.rs @@ -10,7 +10,7 @@ use crate::{ }; use async_trait::async_trait; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_lib_sms::{template_map_to_arr, CloOpenSms, SendError, SendNotifyError, SendNotifyItem}; use lsys_setting::{ dao::{ @@ -254,8 +254,13 @@ impl SenderTaskExecutor for CloOpenSenderTask { tpl_config: &SenderTplConfigModel, setting: &SettingModel, ) -> SenderTaskResult { - let sub_setting = SettingData::::try_from(setting.to_owned()) - .map_err(|e| SenderExecError::Next(format!("parse config to setting fail:{}", e)))?; + let sub_setting = + SettingData::::try_from(setting.to_owned()).map_err(|e| { + SenderExecError::Next(format!( + "parse config to setting fail:{}", + e.to_fluent_message().default_format() + )) + })?; let sub_tpl_config = serde_json::from_str::(&tpl_config.config_data) .map_err(|e| { SenderExecError::Next(format!( diff --git a/server/lsys-sender/src/dao/adapter/smser/sender_huawei.rs b/server/lsys-sender/src/dao/adapter/smser/sender_huawei.rs index 8d014d4..b3dc869 100644 --- a/server/lsys-sender/src/dao/adapter/smser/sender_huawei.rs +++ b/server/lsys-sender/src/dao/adapter/smser/sender_huawei.rs @@ -9,7 +9,7 @@ use crate::{ model::SenderTplConfigModel, }; use async_trait::async_trait; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_setting::{ dao::{ MultipleSetting, SettingData, SettingDecode, SettingEncode, SettingError, SettingKey, @@ -281,7 +281,10 @@ impl SenderTaskExecutor for HwYunSenderTask { ) -> SenderTaskResult { let sub_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to huawei setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to huawei setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let sub_tpl_config = serde_json::from_str::(&tpl_config.config_data) .map_err(|e| { diff --git a/server/lsys-sender/src/dao/adapter/smser/sender_jdcloud.rs b/server/lsys-sender/src/dao/adapter/smser/sender_jdcloud.rs index 366c4b8..0c2c7c5 100644 --- a/server/lsys-sender/src/dao/adapter/smser/sender_jdcloud.rs +++ b/server/lsys-sender/src/dao/adapter/smser/sender_jdcloud.rs @@ -10,7 +10,7 @@ use crate::{ }; use async_trait::async_trait; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_lib_sms::{template_map_to_arr, JdSms, SendDetailItem, SendError}; use lsys_setting::{ dao::{ @@ -264,7 +264,10 @@ impl SenderTaskExecutor for JDCloudSenderTask { ) -> SenderTaskResult { let sub_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to jd_cloud setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to jd_cloud setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let sub_tpl_config = serde_json::from_str::(&tpl_config.config_data) .map_err(|e| { @@ -335,8 +338,13 @@ impl crate::dao::SmsStatusTaskExecutor for JDSendStatus { msg: &SenderSmsMessageModel, setting: &SettingModel, ) -> Result, SenderExecError> { - let setting_data = SettingData::::try_from(setting.to_owned()) - .map_err(|e| SenderExecError::Next(format!("parse config to jd setting fail:{}", e)))?; + let setting_data = + SettingData::::try_from(setting.to_owned()).map_err(|e| { + SenderExecError::Next(format!( + "parse config to jd setting fail:{}", + e.to_fluent_message().default_format() + )) + })?; JdSms::send_detail( create_sender_client()?, diff --git a/server/lsys-sender/src/dao/adapter/smser/sender_netease.rs b/server/lsys-sender/src/dao/adapter/smser/sender_netease.rs index d04434e..ed6f319 100644 --- a/server/lsys-sender/src/dao/adapter/smser/sender_netease.rs +++ b/server/lsys-sender/src/dao/adapter/smser/sender_netease.rs @@ -10,7 +10,7 @@ use crate::{ }; use async_trait::async_trait; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_lib_sms::{ template_map_to_arr, NeteaseSms, SendDetailItem, SendError, SendNotifyError, SendNotifyItem, }; @@ -96,7 +96,7 @@ impl SenderNetEaseConfig { tpl_config, } } - //列出有效的jd_cloud短信配置 + //列出有效的netease短信配置 pub async fn list_config( &self, config_ids: &Option>, @@ -107,7 +107,7 @@ impl SenderNetEaseConfig { .await?; Ok(data) } - //删除指定的jd_cloud短信配置 + //删除指定的netease短信配置 pub async fn del_config( &self, id: &u64, @@ -119,7 +119,7 @@ impl SenderNetEaseConfig { .del::(&None, id, user_id, None, env_data) .await?) } - //编辑指定的jd_cloud短信配置 + //编辑指定的netease短信配置 #[allow(clippy::too_many_arguments)] pub async fn edit_config( @@ -156,7 +156,7 @@ impl SenderNetEaseConfig { ) .await?) } - //添加jd_cloud短信配置 + //添加netease短信配置 pub async fn add_config( &self, name: &str, @@ -189,7 +189,7 @@ impl SenderNetEaseConfig { ) .await?) } - //关联发送跟jd_cloud短信的配置 + //关联发送跟netease短信的配置 #[allow(clippy::too_many_arguments)] pub async fn add_app_config( &self, @@ -255,12 +255,15 @@ impl SenderTaskExecutor for NetEaseSenderTask { ) -> SenderTaskResult { let sub_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to jd_cloud setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to netease setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let sub_tpl_config = serde_json::from_str::(&tpl_config.config_data) .map_err(|e| { SenderExecError::Next(format!( - "parse config to jd_cloud tpl config fail[{}]:{}", + "parse config to netease tpl config fail[{}]:{}", sub_setting.access_key, e )) })?; @@ -354,7 +357,10 @@ impl crate::dao::SmsStatusTaskExecutor for NetEaseSendStatus { ) -> Result, SenderExecError> { let setting_data = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to netease setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to netease setting fail:{}", + e.to_fluent_message().default_format() + )) })?; NeteaseSms::send_detail( diff --git a/server/lsys-sender/src/dao/adapter/smser/sender_tencent.rs b/server/lsys-sender/src/dao/adapter/smser/sender_tencent.rs index 8ce1761..41dfe07 100644 --- a/server/lsys-sender/src/dao/adapter/smser/sender_tencent.rs +++ b/server/lsys-sender/src/dao/adapter/smser/sender_tencent.rs @@ -11,7 +11,7 @@ use crate::{ use async_trait::async_trait; use chrono::NaiveDateTime; -use lsys_core::{fluent_message, RequestEnv}; +use lsys_core::{fluent_message, IntoFluentMessage, RequestEnv}; use lsys_lib_sms::{ template_map_to_arr, SendDetailItem, SendError, SendNotifyError, SendNotifyItem, TenSms, }; @@ -275,7 +275,10 @@ impl SenderTaskExecutor for TenyunSenderTask { ) -> SenderTaskResult { let sub_setting = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to tenyun setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to tenyun setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let sub_tpl_config = serde_json::from_str::(&tpl_config.config_data) .map_err(|e| { @@ -389,7 +392,10 @@ impl crate::dao::SmsStatusTaskExecutor for TenYunSendStatus { ) -> Result, SenderExecError> { let setting_data = SettingData::::try_from(setting.to_owned()).map_err(|e| { - SenderExecError::Next(format!("parse config to ten yun setting fail:{}", e)) + SenderExecError::Next(format!( + "parse config to ten yun setting fail:{}", + e.to_fluent_message().default_format() + )) })?; let naive_date_time = NaiveDateTime::from_timestamp_opt(msg.send_time as i64, 0).unwrap_or_default(); diff --git a/server/lsys-sender/src/dao/mod.rs b/server/lsys-sender/src/dao/mod.rs index 4a308b9..45dad69 100644 --- a/server/lsys-sender/src/dao/mod.rs +++ b/server/lsys-sender/src/dao/mod.rs @@ -4,7 +4,6 @@ mod message_cancel; mod message_logs; mod message_reader; mod message_tpls; -mod sender; mod sender_config; mod sender_mailer; mod sender_smser; @@ -16,10 +15,11 @@ pub use message_cancel::*; pub use message_logs::*; pub use message_reader::*; pub use message_tpls::*; -pub use sender::*; pub use sender_config::*; pub use sender_mailer::*; pub use sender_smser::*; pub use sender_task::*; pub use sender_tpl_config::*; pub(crate) use sender_wait::*; +mod result; +pub use result::*; diff --git a/server/lsys-sender/src/dao/result.rs b/server/lsys-sender/src/dao/result.rs new file mode 100644 index 0000000..1c2143c --- /dev/null +++ b/server/lsys-sender/src/dao/result.rs @@ -0,0 +1,98 @@ +use std::{ + // error::Error, + fmt::{Display, Formatter}, +}; + +use deadpool_redis::PoolError; +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage}; +use lsys_setting::dao::SettingError; + +//公共结构定义 +#[derive(Debug)] +pub enum SenderError { + Sqlx(sqlx::Error), + Redis(redis::RedisError), + RedisPool(PoolError), + Tera(tera::Error), + System(FluentMessage), + Setting(SettingError), +} + +impl IntoFluentMessage for SenderError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + SenderError::Sqlx(err) => fluent_message!("sqlx-error", err), + SenderError::Redis(err) => fluent_message!("redis-error", err), + SenderError::RedisPool(err) => fluent_message!("redis-error", err), + SenderError::Tera(err) => fluent_message!("tera-error", err), + SenderError::System(err) => err.to_owned(), + SenderError::Setting(err) => err.to_fluent_message(), + } + } +} + +// impl Display for SenderError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } + +// impl Error for SenderError {} + +impl From for SenderError { + fn from(err: sqlx::Error) -> Self { + SenderError::Sqlx(err) + } +} +impl From for SenderError { + fn from(err: redis::RedisError) -> Self { + SenderError::Redis(err) + } +} +impl From for SenderError { + fn from(err: PoolError) -> Self { + SenderError::RedisPool(err) + } +} +impl From for SenderError { + fn from(err: SettingError) -> Self { + SenderError::Setting(err) + } +} +impl From for SenderError { + fn from(err: tera::Error) -> Self { + SenderError::Tera(err) + } +} + +pub type SenderResult = Result; + +#[derive(Debug)] +pub enum SenderExecError { + Finish(String), + Next(String), +} + +impl Display for SenderExecError { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + Self::Finish(e) => write!(f, "{}", e), + Self::Next(e) => write!(f, "{}", e), + } + } +} + +pub enum SenderTaskStatus { + Progress, + Completed, + Failed(bool), //失败是否重试 +} + +pub struct SenderTaskResultItem { + pub id: u64, // SenderTaskData item id + pub status: SenderTaskStatus, + pub message: String, + pub send_id: String, +} + +pub type SenderTaskResult = Result, SenderExecError>; diff --git a/server/lsys-sender/src/dao/sender.rs b/server/lsys-sender/src/dao/sender.rs index 93bdae4..8b13789 100644 --- a/server/lsys-sender/src/dao/sender.rs +++ b/server/lsys-sender/src/dao/sender.rs @@ -1,54 +1 @@ -use std::{ - error::Error, - fmt::{Display, Formatter}, -}; -use deadpool_redis::PoolError; -use lsys_core::FluentMessage; -use lsys_setting::dao::SettingError; - -//公共结构定义 -#[derive(Debug)] -pub enum SenderError { - Sqlx(sqlx::Error), - Redis(redis::RedisError), - RedisPool(PoolError), - Tera(tera::Error), - System(FluentMessage), - Setting(SettingError), -} -impl Display for SenderError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl Error for SenderError {} - -impl From for SenderError { - fn from(err: sqlx::Error) -> Self { - SenderError::Sqlx(err) - } -} -impl From for SenderError { - fn from(err: redis::RedisError) -> Self { - SenderError::Redis(err) - } -} -impl From for SenderError { - fn from(err: PoolError) -> Self { - SenderError::RedisPool(err) - } -} -impl From for SenderError { - fn from(err: SettingError) -> Self { - SenderError::Setting(err) - } -} -impl From for SenderError { - fn from(err: tera::Error) -> Self { - SenderError::Tera(err) - } -} - -pub type SenderResult = Result; diff --git a/server/lsys-sender/src/dao/sender_mailer/record.rs b/server/lsys-sender/src/dao/sender_mailer/record.rs index a30b1c6..a4f3b3b 100644 --- a/server/lsys-sender/src/dao/sender_mailer/record.rs +++ b/server/lsys-sender/src/dao/sender_mailer/record.rs @@ -649,7 +649,7 @@ impl MailRecord { fluent_message!("mail-send-check-limit", // "trigger limit rule :{} on {} [{}]", { "max_send":limit.max_send, - "to_mail":t.2, + "to_mail":&t.2, "config_id":id } ), diff --git a/server/lsys-sender/src/dao/sender_mailer/send_task.rs b/server/lsys-sender/src/dao/sender_mailer/send_task.rs index 6f7ad4f..175c925 100644 --- a/server/lsys-sender/src/dao/sender_mailer/send_task.rs +++ b/server/lsys-sender/src/dao/sender_mailer/send_task.rs @@ -10,7 +10,7 @@ use crate::{ }, }; use async_trait::async_trait; -use lsys_core::{fluent_message, now_time}; +use lsys_core::{fluent_message, now_time, IntoFluentMessage}; use lsys_core::{TaskAcquisition, TaskData, TaskExecutor, TaskItem, TaskRecord}; use lsys_setting::model::SettingModel; use sqlx_model::{ModelTableName, SqlExpr, SqlQuote}; @@ -146,7 +146,7 @@ impl SenderTaskAcquisition for MailTaskAcquisit limit, ) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_fluent_message().default_format())?; if app_res.is_empty() { let sql_where = sql_format!( @@ -486,7 +486,7 @@ impl TaskAcquisition for MailTaskAcquisition { .message_reader .read_task(tasking_record, SenderMailMessageStatus::Init as i8, limit) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_fluent_message().default_format())?; let app_res = app_res .into_iter() .map(|e| MailTaskItem { mail: e }) diff --git a/server/lsys-sender/src/dao/sender_mailer/sender.rs b/server/lsys-sender/src/dao/sender_mailer/sender.rs index e5b2451..0490010 100644 --- a/server/lsys-sender/src/dao/sender_mailer/sender.rs +++ b/server/lsys-sender/src/dao/sender_mailer/sender.rs @@ -15,6 +15,7 @@ use crate::{ }, model::{SenderMailBodyModel, SenderMailMessageModel, SenderType}, }; +use lsys_core::IntoFluentMessage; use lsys_core::TaskDispatch; const MAILER_REDIS_PREFIX: &str = "sender-mail-"; @@ -173,7 +174,12 @@ impl MailSender { .wait_timeout(t) .await .map(|e| e.map_err(|c| fluent_message!("mail-send-fail", c))) - .unwrap_or_else(|e| Err(fluent_message!("mail-send-wait-fail", e))) + .unwrap_or_else(|e| { + Err(fluent_message!( + "mail-send-wait-fail", + e.to_fluent_message() + )) + }) } else { Ok(true) }; @@ -213,7 +219,7 @@ impl MailSender { Some(SenderError::System( fluent_message!("mail-send-ok-cancel", // "mail {} is send:{}", { - "to_mail":msg.to_mail, + "to_mail":&msg.to_mail, "msg_id":msg.id } ), diff --git a/server/lsys-sender/src/dao/sender_smser/notify.rs b/server/lsys-sender/src/dao/sender_smser/notify.rs index fd71f52..f5994af 100644 --- a/server/lsys-sender/src/dao/sender_smser/notify.rs +++ b/server/lsys-sender/src/dao/sender_smser/notify.rs @@ -8,6 +8,7 @@ use crate::{ }, }; +use lsys_core::IntoFluentMessage; use lsys_lib_sms::{SendNotifyError, SendNotifyItem, SendNotifyStatus}; use lsys_notify::dao::{Notify, NotifyData}; use lsys_setting::{ @@ -60,7 +61,10 @@ pub(crate) async fn add_notify_callback( } }; if let Err(err) = notify.add_data(NotifySmsItem { app_id, sms }).await { - warn!("add notify data fail:{}", err); + warn!( + "add notify data fail:{}", + err.to_fluent_message().default_format() + ); } } @@ -131,7 +135,10 @@ impl SmsSendNotify { let sms_config = match SettingData::try_from(config) { Ok(c) => c, Err(e) => { - return Err(format!("parse setting fail:{}", e)); + return Err(format!( + "parse setting fail:{}", + e.to_fluent_message().default_format() + )); } }; let items = data.notify_items(&sms_config).map_err(|e| match e { diff --git a/server/lsys-sender/src/dao/sender_smser/record.rs b/server/lsys-sender/src/dao/sender_smser/record.rs index c527719..863925e 100644 --- a/server/lsys-sender/src/dao/sender_smser/record.rs +++ b/server/lsys-sender/src/dao/sender_smser/record.rs @@ -674,8 +674,8 @@ impl SmsRecord { fluent_message!("sms-send-check-limit", // "trigger limit rule :{} on {} [{}]", { "max_send":limit.max_send, - "area":t.2, - "mobile":t.3, + "area":&t.2, + "mobile":&t.3, "config_id":id } ), diff --git a/server/lsys-sender/src/dao/sender_smser/send_task.rs b/server/lsys-sender/src/dao/sender_smser/send_task.rs index e94cba0..ee5da6f 100644 --- a/server/lsys-sender/src/dao/sender_smser/send_task.rs +++ b/server/lsys-sender/src/dao/sender_smser/send_task.rs @@ -4,7 +4,7 @@ use std::{ }; use async_trait::async_trait; -use lsys_core::{fluent_message, now_time}; +use lsys_core::{fluent_message, now_time, IntoFluentMessage}; use crate::{ dao::{ @@ -159,7 +159,7 @@ impl SenderTaskAcquisition for SmsTaskAcquisition limit, ) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_fluent_message().default_format())?; if app_res.is_empty() { let sql_where = sql_format!( @@ -496,7 +496,7 @@ impl TaskAcquisition for SmsTaskAcquisition { .message_reader .read_task(tasking_record, SenderSmsBodyStatus::Init as i8, limit) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_fluent_message().default_format())?; let app_res = app_res .into_iter() .map(|e| SmsTaskItem { sms: e }) diff --git a/server/lsys-sender/src/dao/sender_smser/sender.rs b/server/lsys-sender/src/dao/sender_smser/sender.rs index 56029a3..7a42744 100644 --- a/server/lsys-sender/src/dao/sender_smser/sender.rs +++ b/server/lsys-sender/src/dao/sender_smser/sender.rs @@ -1,6 +1,8 @@ use std::{collections::HashSet, sync::Arc}; -use lsys_core::{fluent_message, now_time, AppCore, FluentMessage, RequestEnv, TaskData}; +use lsys_core::{ + fluent_message, now_time, AppCore, FluentMessage, IntoFluentMessage, RequestEnv, TaskData, +}; use lsys_logger::dao::ChangeLogger; use lsys_notify::dao::Notify; @@ -221,7 +223,9 @@ impl SmsSender { .wait_timeout(t) .await .map(|e| e.map_err(|c| fluent_message!("sms-send-fail", c))) - .unwrap_or_else(|e| Err(fluent_message!("sms-send-wait-fail", e))) + .unwrap_or_else(|e| { + Err(fluent_message!("sms-send-wait-fail", e.to_fluent_message())) + }) } else { Ok(true) }; @@ -290,7 +294,7 @@ impl SmsSender { Some(SenderError::System( fluent_message!("sms-send-ok-cancel", // "sms {} is sending:{}", { - "mobile":msg.mobile, + "mobile":&msg.mobile, "msg_id":msg.id } ), diff --git a/server/lsys-sender/src/dao/sender_smser/status_task.rs b/server/lsys-sender/src/dao/sender_smser/status_task.rs index d504b34..7642f4c 100644 --- a/server/lsys-sender/src/dao/sender_smser/status_task.rs +++ b/server/lsys-sender/src/dao/sender_smser/status_task.rs @@ -4,6 +4,7 @@ use async_trait::async_trait; use lsys_core::fluent_message; use lsys_core::now_time; +use lsys_core::IntoFluentMessage; use lsys_notify::dao::Notify; use lsys_setting::dao::MultipleSetting; @@ -198,13 +199,13 @@ impl TaskExecutor for SmsStatusTask { .recrod .find_message_by_id(&val.0) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_fluent_message().default_format())?; let body = self .recrod .find_body_by_id(&sms.sender_body_id) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_fluent_message().default_format())?; match self.setting.find(&None, &sms.setting_id).await { Ok(setting) => { @@ -305,7 +306,7 @@ impl TaskExecutor for SmsStatusTask { } } Err(err) => { - return Err(err.to_string()); + return Err(err.to_fluent_message().default_format()); } }; return Err(format!("not find any status apatar :{}", val.0)); diff --git a/server/lsys-sender/src/dao/sender_task.rs b/server/lsys-sender/src/dao/sender_task.rs index 6f873a9..c12c33e 100644 --- a/server/lsys-sender/src/dao/sender_task.rs +++ b/server/lsys-sender/src/dao/sender_task.rs @@ -1,6 +1,6 @@ use std::{ collections::{hash_map::Entry, HashMap}, - fmt::{Display, Formatter}, + fmt::Display, hash::Hash, sync::atomic::AtomicU32, }; @@ -8,7 +8,7 @@ use std::{ use async_trait::async_trait; use futures::{stream::FuturesUnordered, FutureExt, StreamExt}; -use lsys_core::{TaskAcquisition, TaskItem}; +use lsys_core::{IntoFluentMessage, TaskAcquisition, TaskItem}; use lsys_setting::model::SettingModel; use redis::{FromRedisValue, ToRedisArgs}; @@ -16,26 +16,11 @@ use tracing::warn; use crate::model::SenderTplConfigModel; -use super::SenderTplConfig; +use super::{SenderExecError, SenderTaskResult, SenderTaskResultItem, SenderTplConfig}; //在发送任务封装下 //增加多个发送适配支持 -#[derive(Debug)] -pub enum SenderExecError { - Finish(String), - Next(String), -} - -impl Display for SenderExecError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - Self::Finish(e) => write!(f, "{:?}", e), - Self::Next(e) => write!(f, "{:?}", e), - } - } -} - pub(crate) fn index_get(index_store: &AtomicU32, len: usize) -> usize { if len > 1 { let mut now = index_store.fetch_add(1, std::sync::atomic::Ordering::Relaxed) as usize; @@ -96,21 +81,6 @@ pub trait SenderTaskAcquisition< ); } -pub enum SenderTaskStatus { - Progress, - Completed, - Failed(bool), //失败是否重试 -} - -pub struct SenderTaskResultItem { - pub id: u64, // SenderTaskData item id - pub status: SenderTaskStatus, - pub message: String, - pub send_id: String, -} - -pub type SenderTaskResult = Result, SenderExecError>; - #[async_trait] pub trait SenderTaskExecutor< I: FromRedisValue + ToRedisArgs + Eq + Hash + Send + Sync + Display, @@ -169,7 +139,7 @@ pub(crate) async fn group_exec< &None, ) .await - .map_err(|e| e.to_string()) + .map_err(|e| e.to_fluent_message().default_format()) { Ok(t) => t, Err(err) => { diff --git a/server/lsys-setting/src/dao/mod.rs b/server/lsys-setting/src/dao/mod.rs index 6f1960d..0acad0b 100644 --- a/server/lsys-setting/src/dao/mod.rs +++ b/server/lsys-setting/src/dao/mod.rs @@ -5,3 +5,6 @@ mod setting_single; pub use setting::*; pub use setting_multiple::*; pub use setting_single::*; + +mod result; +pub use result::*; diff --git a/server/lsys-setting/src/dao/result.rs b/server/lsys-setting/src/dao/result.rs new file mode 100644 index 0000000..4a49501 --- /dev/null +++ b/server/lsys-setting/src/dao/result.rs @@ -0,0 +1,49 @@ +// use std::error::Error; +// use std::fmt::{Display, Formatter}; + +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage}; +#[derive(Debug)] +pub enum SettingError { + Sqlx(sqlx::Error), + SerdeJson(serde_json::Error), + // System(FluentMessage), +} + +impl IntoFluentMessage for SettingError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + Self::Sqlx(err) => fluent_message!("sqlx-error", err), + Self::SerdeJson(err) => fluent_message!("serde-error", err), + } + } +} + +// impl Display for SettingError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } + +// impl Error for SettingError {} + +impl From for SettingError { + fn from(err: sqlx::Error) -> Self { + SettingError::Sqlx(err) + } +} + +pub type SettingResult = Result; + +pub trait NotFoundResult { + fn notfound_default(self) -> Self; +} + +impl NotFoundResult for SettingResult { + fn notfound_default(self) -> Self { + match self { + Ok(s) => Ok(s), + Err(SettingError::Sqlx(sqlx::Error::RowNotFound)) => Ok(T::default()), + Err(e) => Err(e), + } + } +} diff --git a/server/lsys-setting/src/dao/setting.rs b/server/lsys-setting/src/dao/setting.rs index 86878c9..7ea7364 100644 --- a/server/lsys-setting/src/dao/setting.rs +++ b/server/lsys-setting/src/dao/setting.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use std::error::Error; -use std::fmt::{Display, Formatter}; +// use std::error::Error; + use std::ops::Deref; use lsys_logger::dao::ChangeLogData; @@ -11,7 +11,7 @@ use crate::model::{SettingModel, SettingStatus, SettingType}; use sqlx::{MySql, Pool}; use std::sync::Arc; -use super::{MultipleSetting, SingleSetting}; +use super::{MultipleSetting, SettingError, SettingResult, SingleSetting}; use lsys_core::{AppCoreError, RemoteNotify}; use lsys_logger::dao::ChangeLogger; @@ -67,42 +67,6 @@ impl Setting { ); } -#[derive(Debug)] -pub enum SettingError { - Sqlx(sqlx::Error), - SerdeJson(serde_json::Error), - // System(FluentMessage), -} -impl Display for SettingError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl Error for SettingError {} - -impl From for SettingError { - fn from(err: sqlx::Error) -> Self { - SettingError::Sqlx(err) - } -} - -pub type SettingResult = Result; - -pub trait NotFoundResult { - fn notfound_default(self) -> Self; -} - -impl NotFoundResult for SettingResult { - fn notfound_default(self) -> Self { - match self { - Ok(s) => Ok(s), - Err(SettingError::Sqlx(sqlx::Error::RowNotFound)) => Ok(T::default()), - Err(e) => Err(e), - } - } -} - pub trait SettingKey { fn key<'t>() -> &'t str; } diff --git a/server/lsys-setting/src/dao/setting_multiple.rs b/server/lsys-setting/src/dao/setting_multiple.rs index daa0256..62014f8 100644 --- a/server/lsys-setting/src/dao/setting_multiple.rs +++ b/server/lsys-setting/src/dao/setting_multiple.rs @@ -1,5 +1,5 @@ use lsys_core::cache::{LocalCache, LocalCacheConfig}; -use lsys_core::{now_time, PageParam, RemoteNotify, RequestEnv}; +use lsys_core::{now_time, IntoFluentMessage, PageParam, RemoteNotify, RequestEnv}; use lsys_logger::dao::ChangeLogger; use sqlx::{MySql, Pool, Transaction}; use sqlx_model::{ @@ -263,7 +263,10 @@ impl MultipleSetting { out.push(dat); } Err(err) => { - warn!("setting parse fail:{}", err); + warn!( + "setting parse fail:{}", + err.to_fluent_message().default_format() + ); } } } diff --git a/server/lsys-user/src/dao/account/mod.rs b/server/lsys-user/src/dao/account/mod.rs index a649386..46922e0 100644 --- a/server/lsys-user/src/dao/account/mod.rs +++ b/server/lsys-user/src/dao/account/mod.rs @@ -1,19 +1,19 @@ -use std::error::Error; -use std::fmt::{Display, Formatter}; +// use std::error::Error; + + -use std::time::SystemTimeError; use self::user_index::UserIndex; use self::user_login::UserLogin; use super::auth::UserPasswordHash; -use deadpool_redis::PoolError; -use lsys_core::{fluent_message, FluentMessage, RemoteNotify, ValidCodeError}; + +use lsys_core::{RemoteNotify}; use lsys_logger::dao::ChangeLogger; -use lsys_setting::dao::{SettingError, SingleSetting}; -use redis::RedisError; +use lsys_setting::dao::{SingleSetting}; + use sqlx::{MySql, Pool}; use std::sync::Arc; use user::User; @@ -28,8 +28,10 @@ use user_password::UserPassword; mod macros; mod logger; +mod result; mod user_index; mod utils; +pub use result::*; pub use utils::*; pub mod cache; pub mod user; @@ -42,63 +44,6 @@ pub mod user_mobile; pub mod user_name; pub mod user_password; -#[derive(Debug)] -pub enum UserAccountError { - Sqlx(sqlx::Error), - System(FluentMessage), - Status((u64, FluentMessage)), - Redis(RedisError), - RedisPool(PoolError), - ValidCode(ValidCodeError), - Setting(SettingError), - Param(FluentMessage), -} -impl Display for UserAccountError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl Error for UserAccountError {} - -impl UserAccountError { - pub fn is_not_found(&self) -> bool { - matches!(self, UserAccountError::Sqlx(sqlx::Error::RowNotFound)) - } -} - -pub type UserAccountResult = Result; - -impl From for UserAccountError { - fn from(err: sqlx::Error) -> Self { - UserAccountError::Sqlx(err) - } -} -impl From for UserAccountError { - fn from(err: RedisError) -> Self { - UserAccountError::Redis(err) - } -} -impl From for UserAccountError { - fn from(err: PoolError) -> Self { - UserAccountError::RedisPool(err) - } -} -impl From for UserAccountError { - fn from(err: SystemTimeError) -> Self { - UserAccountError::System(fluent_message!("time-error", err)) - } -} - -impl From for UserAccountError { - fn from(err: ValidCodeError) -> Self { - UserAccountError::ValidCode(err) - } -} -impl From for UserAccountError { - fn from(err: SettingError) -> Self { - UserAccountError::Setting(err) - } -} pub struct UserAccount { pub user: Arc, pub user_email: Arc, diff --git a/server/lsys-user/src/dao/account/result.rs b/server/lsys-user/src/dao/account/result.rs new file mode 100644 index 0000000..703300c --- /dev/null +++ b/server/lsys-user/src/dao/account/result.rs @@ -0,0 +1,83 @@ +// use std::error::Error; +// use std::fmt::{Display, Formatter}; + +use std::time::SystemTimeError; + +use deadpool_redis::PoolError; +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage, ValidCodeError}; + +use lsys_setting::dao::SettingError; +use redis::RedisError; +#[derive(Debug)] +pub enum UserAccountError { + Sqlx(sqlx::Error), + System(FluentMessage), + Status((u64, FluentMessage)), + Redis(RedisError), + RedisPool(PoolError), + ValidCode(ValidCodeError), + Setting(SettingError), + Param(FluentMessage), +} + +impl IntoFluentMessage for UserAccountError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + UserAccountError::Sqlx(err) => fluent_message!("sqlx-error", err), + UserAccountError::System(err) => err.to_owned(), + UserAccountError::Status((_, err)) => err.to_owned(), + UserAccountError::Redis(err) => fluent_message!("redis-error", err), + UserAccountError::RedisPool(err) => fluent_message!("redis-error", err), + UserAccountError::ValidCode(err) => err.to_fluent_message(), + UserAccountError::Setting(err) => err.to_fluent_message(), + UserAccountError::Param(err) => err.to_owned(), + } + } +} + +// impl Display for UserAccountError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +// impl Error for UserAccountError {} + +impl UserAccountError { + pub fn is_not_found(&self) -> bool { + matches!(self, UserAccountError::Sqlx(sqlx::Error::RowNotFound)) + } +} + +pub type UserAccountResult = Result; + +impl From for UserAccountError { + fn from(err: sqlx::Error) -> Self { + UserAccountError::Sqlx(err) + } +} +impl From for UserAccountError { + fn from(err: RedisError) -> Self { + UserAccountError::Redis(err) + } +} +impl From for UserAccountError { + fn from(err: PoolError) -> Self { + UserAccountError::RedisPool(err) + } +} +impl From for UserAccountError { + fn from(err: SystemTimeError) -> Self { + UserAccountError::System(fluent_message!("time-error", err)) + } +} + +impl From for UserAccountError { + fn from(err: ValidCodeError) -> Self { + UserAccountError::ValidCode(err) + } +} +impl From for UserAccountError { + fn from(err: SettingError) -> Self { + UserAccountError::Setting(err) + } +} diff --git a/server/lsys-user/src/dao/account/user.rs b/server/lsys-user/src/dao/account/user.rs index c628523..2cf3286 100644 --- a/server/lsys-user/src/dao/account/user.rs +++ b/server/lsys-user/src/dao/account/user.rs @@ -138,7 +138,7 @@ impl User { ) -> UserAccountResult<()> { if UserStatus::Delete.eq(user.status) { return Err(UserAccountError::System(fluent_message!("user-is-delete",{ - "user":user.nickname + "user":&user.nickname }))); } if UserStatus::Enable.eq(user.status) { diff --git a/server/lsys-user/src/dao/account/user_email.rs b/server/lsys-user/src/dao/account/user_email.rs index c80cc3c..81b8cb5 100644 --- a/server/lsys-user/src/dao/account/user_email.rs +++ b/server/lsys-user/src/dao/account/user_email.rs @@ -5,7 +5,7 @@ use crate::dao::account::UserAccountResult; use crate::model::{UserEmailModel, UserEmailModelRef, UserEmailStatus, UserModel}; use lsys_core::cache::{LocalCache, LocalCacheConfig}; -use lsys_core::{fluent_message, now_time, RemoteNotify, RequestEnv}; +use lsys_core::{fluent_message, now_time, IntoFluentMessage, RemoteNotify, RequestEnv}; use lsys_logger::dao::ChangeLogger; use sqlx::{Acquire, MySql, Pool, Transaction}; @@ -199,7 +199,11 @@ impl UserEmail { let res = self.confirm_email(email, env_data).await; if res.is_ok() { if let Err(err) = self.valid_code_clear(&email.user_id, &email.email).await { - warn!("email {} valid clear fail:{}", &email.email, err); + warn!( + "email {} valid clear fail:{}", + &email.email, + err.to_fluent_message().default_format() + ); } } res diff --git a/server/lsys-user/src/dao/account/user_mobile.rs b/server/lsys-user/src/dao/account/user_mobile.rs index 4fd1ac3..606e4bd 100644 --- a/server/lsys-user/src/dao/account/user_mobile.rs +++ b/server/lsys-user/src/dao/account/user_mobile.rs @@ -5,8 +5,8 @@ use crate::dao::account::UserAccountResult; use crate::model::{UserMobileModel, UserMobileModelRef, UserMobileStatus, UserModel}; use lsys_core::cache::{LocalCache, LocalCacheConfig}; -use lsys_core::RequestEnv; use lsys_core::{fluent_message, now_time, RemoteNotify}; +use lsys_core::{IntoFluentMessage, RequestEnv}; use lsys_logger::dao::ChangeLogger; use sqlx::{Acquire, MySql, Pool, Transaction}; @@ -219,7 +219,9 @@ impl UserMobile { { warn!( "mobile {}-{} valid clear fail:{}", - &user_mobile.area_code, &user_mobile.mobile, err + &user_mobile.area_code, + &user_mobile.mobile, + err.to_fluent_message().default_format() ); } } diff --git a/server/lsys-user/src/dao/account/user_name.rs b/server/lsys-user/src/dao/account/user_name.rs index 241e2c2..2f9c6d4 100644 --- a/server/lsys-user/src/dao/account/user_name.rs +++ b/server/lsys-user/src/dao/account/user_name.rs @@ -260,7 +260,7 @@ impl UserName { Ok(()) } else { Err(UserAccountError::System( - fluent_message!("user-name-exits",{"name":username}), //"name {$name} already exists", + fluent_message!("user-name-exits",{"name":&username}), //"name {$name} already exists", )) } } diff --git a/server/lsys-user/src/dao/account/user_password.rs b/server/lsys-user/src/dao/account/user_password.rs index a8f7ec7..4d16e73 100644 --- a/server/lsys-user/src/dao/account/user_password.rs +++ b/server/lsys-user/src/dao/account/user_password.rs @@ -4,7 +4,7 @@ use crate::dao::account::UserAccountResult; use crate::dao::auth::UserPasswordHash; use crate::model::{UserModel, UserModelRef, UserPasswordModel, UserPasswordModelRef}; -use lsys_core::{fluent_message, now_time}; +use lsys_core::{fluent_message, now_time, IntoFluentMessage}; use lsys_setting::dao::{ NotFoundResult, SettingDecode, SettingEncode, SettingJson, SettingKey, SettingResult, @@ -84,7 +84,11 @@ impl UserPassword { let res = self.set_passwrod(user, new_password, transaction).await; if res.is_ok() { if let Err(err) = self.valid_code_clear(&user.id, from_type).await { - warn!("email {} valid clear fail:{}", &user.id, err); + warn!( + "email {} valid clear fail:{}", + &user.id, + err.to_fluent_message().default_format() + ); } } res diff --git a/server/lsys-user/src/dao/auth/login.rs b/server/lsys-user/src/dao/auth/login.rs index 93d293f..3ddde9a 100644 --- a/server/lsys-user/src/dao/auth/login.rs +++ b/server/lsys-user/src/dao/auth/login.rs @@ -4,7 +4,7 @@ use async_trait::async_trait; use base64::Engine; use ip2location::Record; use lsys_core::cache::{LocalCache, LocalCacheConfig}; -use lsys_core::{fluent_message, RemoteNotify}; +use lsys_core::{fluent_message, IntoFluentMessage, RemoteNotify}; use lsys_core::{now_time, PageParam}; use serde::Deserialize; @@ -372,7 +372,7 @@ impl UserAuth { Err(err) => { warn!( "check captcha fail: {} in account:{}", - err.to_string(), + err.to_fluent_message().default_format(), login_param.show_name() ); } @@ -436,11 +436,11 @@ impl UserAuth { let is_login = i8::from(user_token_res.is_ok()); let login_msg = match &user_token_res { Ok(_) => "".to_string(), - Err(err) => err.to_string(), + Err(err) => err.to_fluent_message().default_format(), }; let login_token = match &user_token_res { Ok(user) => user.to_string(), - Err(err) => err.to_string(), + Err(err) => err.to_fluent_message().default_format(), }; self.account .user_login @@ -457,7 +457,13 @@ impl UserAuth { }; self.account .user_login - .finish_history(login_id, 0, user_id, err.to_string(), "".to_string()) + .finish_history( + login_id, + 0, + user_id, + err.to_fluent_message().default_format(), + "".to_string(), + ) .await?; Err(err) } diff --git a/server/lsys-user/src/dao/auth/login_param/param_email_code.rs b/server/lsys-user/src/dao/auth/login_param/param_email_code.rs index b716622..a37cc76 100644 --- a/server/lsys-user/src/dao/auth/login_param/param_email_code.rs +++ b/server/lsys-user/src/dao/auth/login_param/param_email_code.rs @@ -6,6 +6,7 @@ use crate::dao::auth::{LoginParam, LoginType, UserAuthError, UserAuthResult}; use crate::model::{UserEmailModel, UserModel}; use async_trait::async_trait; +use lsys_core::IntoFluentMessage; use serde::{Deserialize, Serialize}; use sqlx::{MySql, Pool}; use sqlx_model::Select; @@ -79,7 +80,11 @@ impl LoginParam for EmailCodeLogin { user.is_enable()?; if let Err(err) = Self::valid_code_clear(redis.to_owned(), &self.email).await { - warn!("login email clear valid[{}] fail:{}", self.email, err) + warn!( + "login email clear valid[{}] fail:{}", + self.email, + err.to_fluent_message().default_format() + ) } Ok((LoginData::EmailCode(EmailCodeLoginData(email)), user)) diff --git a/server/lsys-user/src/dao/auth/login_param/param_mobile_code.rs b/server/lsys-user/src/dao/auth/login_param/param_mobile_code.rs index 5cf3883..bdbddf8 100644 --- a/server/lsys-user/src/dao/auth/login_param/param_mobile_code.rs +++ b/server/lsys-user/src/dao/auth/login_param/param_mobile_code.rs @@ -6,6 +6,7 @@ use crate::dao::auth::{LoginParam, LoginType, UserAuthError, UserAuthResult}; use crate::model::{UserMobileModel, UserModel}; use async_trait::async_trait; +use lsys_core::IntoFluentMessage; use serde::{Deserialize, Serialize}; use sqlx::{MySql, Pool}; use sqlx_model::Select; @@ -88,7 +89,9 @@ impl LoginParam for MobileCodeLogin { { warn!( "login mobile clear valid[{}-{}] fail:{}", - &self.area_code, &self.mobile, err + &self.area_code, + &self.mobile, + err.to_fluent_message().default_format() ) } diff --git a/server/lsys-user/src/dao/auth/mod.rs b/server/lsys-user/src/dao/auth/mod.rs index 800fba5..4775544 100644 --- a/server/lsys-user/src/dao/auth/mod.rs +++ b/server/lsys-user/src/dao/auth/mod.rs @@ -2,90 +2,25 @@ mod login; mod login_param; mod login_store; mod session; -use deadpool_redis::PoolError; + pub use login::*; pub use login_store::*; pub use session::*; -use crate::dao::account::UserAccountError; -use lsys_core::{fluent_message, FluentMessage, ValidCodeError}; -use redis::RedisError; -use std::error::Error; -use std::fmt::{Display, Formatter}; -use std::string::FromUtf8Error; -use std::time::SystemTimeError; -pub use self::login_param::*; +// use std::error::Error; + + -//统一错误 -#[derive(Debug)] -pub enum UserAuthError { - TokenParse(FluentMessage), - Sqlx(sqlx::Error), - Redis(RedisError), - RedisPool(PoolError), - PasswordNotMatch((u64, FluentMessage)), - PasswordNotSet((u64, FluentMessage)), - StatusError((u64, FluentMessage)), - ValidCode(ValidCodeError), - UserNotFind(FluentMessage), - NotLogin(FluentMessage), - UserAccount(UserAccountError), - System(FluentMessage), - CheckUserLock((u64, FluentMessage)), - CheckCaptchaNeed(FluentMessage), -} -impl Display for UserAuthError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} -impl Error for UserAuthError {} -pub type UserAuthResult = Result; -impl From for UserAuthError { - fn from(err: sqlx::Error) -> Self { - UserAuthError::Sqlx(err) - } -} -impl From for UserAuthError { - fn from(err: SystemTimeError) -> Self { - UserAuthError::System(err.to_string().into()) - } -} -impl From for UserAuthError { - fn from(err: RedisError) -> Self { - UserAuthError::Redis(err) - } -} -impl From for UserAuthError { - fn from(err: PoolError) -> Self { - UserAuthError::RedisPool(err) - } -} -impl From for UserAuthError { - fn from(err: serde_json::Error) -> Self { - UserAuthError::System(fluent_message!("serde-error", err)) - } -} -impl From for UserAuthError { - fn from(err: UserAccountError) -> Self { - UserAuthError::UserAccount(err) - } -} -impl From for UserAuthError { - fn from(err: FromUtf8Error) -> Self { - UserAuthError::System(fluent_message!("utf-error", err)) - } -} -impl From for UserAuthError { - fn from(err: ValidCodeError) -> Self { - UserAuthError::ValidCode(err) - } -} + +pub use self::login_param::*; + +mod result; +pub use result::*; diff --git a/server/lsys-user/src/dao/auth/result.rs b/server/lsys-user/src/dao/auth/result.rs new file mode 100644 index 0000000..743d70d --- /dev/null +++ b/server/lsys-user/src/dao/auth/result.rs @@ -0,0 +1,108 @@ +//统一错误 + +use deadpool_redis::PoolError; + +use crate::dao::account::UserAccountError; +use lsys_core::{fluent_message, FluentMessage, IntoFluentMessage, ValidCodeError}; + +use redis::RedisError; + +// use std::error::Error; +// use std::fmt::{Display, Formatter}; + +use std::string::FromUtf8Error; + +use std::time::SystemTimeError; + +#[derive(Debug)] +pub enum UserAuthError { + TokenParse(FluentMessage), + Sqlx(sqlx::Error), + Redis(RedisError), + RedisPool(PoolError), + PasswordNotMatch((u64, FluentMessage)), + PasswordNotSet((u64, FluentMessage)), + StatusError((u64, FluentMessage)), + ValidCode(ValidCodeError), + UserNotFind(FluentMessage), + NotLogin(FluentMessage), + UserAccount(UserAccountError), + System(FluentMessage), + SerdeJson(serde_json::Error), + CheckUserLock((u64, FluentMessage)), + CheckCaptchaNeed(FluentMessage), + Utf8Err(FromUtf8Error), +} + +impl IntoFluentMessage for UserAuthError { + fn to_fluent_message(&self) -> FluentMessage { + match self { + UserAuthError::TokenParse(err) => err.to_owned(), + UserAuthError::Sqlx(err) => fluent_message!("sqlx-error", err), + UserAuthError::Redis(err) => fluent_message!("redis-error", err), + UserAuthError::RedisPool(err) => fluent_message!("redis-error", err), + UserAuthError::PasswordNotMatch(err) => err.1.to_owned(), + UserAuthError::PasswordNotSet(err) => err.1.to_owned(), + UserAuthError::StatusError(err) => err.1.to_owned(), + UserAuthError::ValidCode(err) => err.to_fluent_message(), + UserAuthError::UserNotFind(err) => err.to_owned(), + UserAuthError::NotLogin(err) => err.to_owned(), + UserAuthError::UserAccount(err) => err.to_fluent_message(), + UserAuthError::System(err) => err.to_owned(), + UserAuthError::CheckUserLock(err) => err.1.to_owned(), + UserAuthError::CheckCaptchaNeed(err) => err.to_owned(), + UserAuthError::SerdeJson(err) => fluent_message!("serde-json-error", err), + UserAuthError::Utf8Err(err) => fluent_message!("utf-parse-error", err), + } + } +} + +// impl Display for UserAuthError { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// write!(f, "{:?}", self) +// } +// } +// impl Error for UserAuthError {} + +pub type UserAuthResult = Result; + +impl From for UserAuthError { + fn from(err: sqlx::Error) -> Self { + UserAuthError::Sqlx(err) + } +} +impl From for UserAuthError { + fn from(err: SystemTimeError) -> Self { + UserAuthError::System(fluent_message!("time-error", err)) + } +} +impl From for UserAuthError { + fn from(err: RedisError) -> Self { + UserAuthError::Redis(err) + } +} +impl From for UserAuthError { + fn from(err: PoolError) -> Self { + UserAuthError::RedisPool(err) + } +} +impl From for UserAuthError { + fn from(err: serde_json::Error) -> Self { + UserAuthError::SerdeJson(err) + } +} +impl From for UserAuthError { + fn from(err: UserAccountError) -> Self { + UserAuthError::UserAccount(err) + } +} +impl From for UserAuthError { + fn from(err: FromUtf8Error) -> Self { + UserAuthError::Utf8Err(err) + } +} +impl From for UserAuthError { + fn from(err: ValidCodeError) -> Self { + UserAuthError::ValidCode(err) + } +} diff --git a/server/lsys-web/src/common/fluents.rs b/server/lsys-web/src/common/fluents.rs new file mode 100644 index 0000000..7e8f2dd --- /dev/null +++ b/server/lsys-web/src/common/fluents.rs @@ -0,0 +1,98 @@ +use lsys_core::{ + fluent_message, ConfigError, FluentBundle, FluentMessage, IntoFluentMessage, ValidCodeError, +}; +use lsys_docs::dao::GitDocError; +use lsys_logger::dao::LoggerError; +use lsys_notify::dao::NotifyError; +use lsys_rbac::dao::rbac::UserRbacError; +use lsys_sender::dao::SenderError; +use lsys_setting::dao::SettingError; +use lsys_user::dao::{account::UserAccountError, auth::UserAuthError}; + +use std::num::ParseIntError; + +use lsys_app::dao::AppsError; + +pub trait FluentFormat { + fn fluent_format(&self, fluent: &FluentBundle) -> String; +} +macro_rules! self_error_fluent_string { + ($self_error:ty) => { + impl FluentFormat for $self_error { + fn fluent_format(&self, fluent: &FluentBundle) -> String { + fluent.format_message(&self.to_fluent_message()) + } + } + }; +} +self_error_fluent_string!(UserAccountError); +self_error_fluent_string!(ValidCodeError); +self_error_fluent_string!(UserAuthError); +self_error_fluent_string!(UserRbacError); +self_error_fluent_string!(SettingError); +self_error_fluent_string!(SenderError); +self_error_fluent_string!(AppsError); +self_error_fluent_string!(ConfigError); +self_error_fluent_string!(NotifyError); +self_error_fluent_string!(GitDocError); +self_error_fluent_string!(LoggerError); + +impl FluentFormat for FluentMessage { + fn fluent_format(&self, fluent: &FluentBundle) -> String { + fluent.format_message(self) + } +} + +impl FluentFormat for area_db::AreaError { + fn fluent_format(&self, fluent: &FluentBundle) -> String { + match self { + area_db::AreaError::DB(err) => { + fluent.format_message(&fluent_message!("area-db-error", err)) + } + area_db::AreaError::System(err) => { + fluent.format_message(&fluent_message!("area-error", err)) + } + area_db::AreaError::NotFind(_) => { + fluent.format_message(&fluent_message!("area-not-found")) + } + area_db::AreaError::Store(err) => { + fluent.format_message(&fluent_message!("area-store-error", err)) + } + area_db::AreaError::Tantivy(err) => { + fluent.format_message(&fluent_message!("area-tantivy-error", err)) + } + } + } +} + +//crate error + +macro_rules! crate_error_fluent_string { + ($crate_error:ty,$key:literal) => { + impl FluentFormat for $crate_error { + fn fluent_format(&self, fluent: &FluentBundle) -> String { + fluent.format_message(&fluent_message!($key, self)) + } + } + }; +} +impl FluentFormat for sqlx::Error { + fn fluent_format(&self, fluent: &FluentBundle) -> String { + match self { + sqlx::Error::RowNotFound => { + fluent.format_message(&fluent_message!("db-not-found", self)) + } + _ => fluent.format_message(&fluent_message!("db-error", self)), + } + } +} + +crate_error_fluent_string!(config::ConfigError, "config-error"); +crate_error_fluent_string!(std::io::Error, "io-error"); +crate_error_fluent_string!(tera::Error, "tera-error"); +crate_error_fluent_string!(lsys_docs::GitError, "git-error"); +crate_error_fluent_string!(redis::RedisError, "redis-error"); +crate_error_fluent_string!(deadpool_redis::PoolError, "redis-error"); +crate_error_fluent_string!(serde_json::Error, "serde-json-error"); +crate_error_fluent_string!(ParseIntError, "parse-error"); +crate_error_fluent_string!(std::string::FromUtf8Error, "utf8-parse-error"); diff --git a/server/lsys-web/src/common/json_result.rs b/server/lsys-web/src/common/json_result.rs new file mode 100644 index 0000000..09e66cd --- /dev/null +++ b/server/lsys-web/src/common/json_result.rs @@ -0,0 +1,315 @@ +use lsys_core::{ConfigError, FluentBundle, FluentMessage, ValidCodeError}; +use lsys_docs::dao::GitDocError; +use lsys_logger::dao::LoggerError; +use lsys_notify::dao::NotifyError; +use lsys_rbac::dao::rbac::UserRbacError; +use lsys_sender::dao::SenderError; +use lsys_setting::dao::SettingError; +use lsys_user::dao::{account::UserAccountError, auth::UserAuthError}; +use serde_json::{json, Value}; + +use std::{collections::HashMap, num::ParseIntError}; + +use crate::FluentFormat; +use lsys_app::dao::AppsError; + +pub trait FluentJsonData { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData; +} + +pub type JsonResult = Result; + +#[derive(Debug, Clone)] +pub struct JsonData { + code: String, + sub_code: String, + message: String, + data: Option, +} +impl Default for JsonData { + fn default() -> Self { + JsonData { + code: "200".to_string(), + sub_code: "ok".to_string(), + message: "ok".to_string(), + data: None, + } + } +} +impl JsonData { + pub fn fluent_from( + fluent: &FluentBundle, + data: T, + ) -> JsonData { + data.set_data( + JsonData::default().set_message(data.fluent_format(fluent)), + fluent, + ) + } + pub fn data(value: Value) -> Self { + JsonData::default().set_message("ok").set_data(value) + } + pub fn error(error: T) -> Self { + JsonData::message_error(format!("error:{}", error)) + } + pub fn message_error(msg: T) -> Self { + JsonData::message(msg).set_code(500).set_sub_code("system") + } + pub fn message(msg: T) -> Self { + JsonData::default().set_message(msg) + } + pub fn set_data(mut self, value: Value) -> Self { + self.data = Some(value); + self + } + pub fn set_total_data(mut self, value: Value, total: T) -> Self { + self.data = Some(json!({ + "total":total.to_string(), + "data":value, + })); + self + } + pub fn set_code(mut self, code: T) -> Self { + self.code = code.to_string(); + self + } + pub fn set_sub_code(mut self, sub_code: T) -> Self { + self.sub_code = sub_code.to_string(); + self + } + pub fn set_message(mut self, msg: T) -> Self { + self.message = msg.to_string(); + self + } + pub fn to_value(&self) -> Value { + if self.data.is_none() { + json!({ + "result": { + "code": self.code, + "state":self.sub_code, + "message": self.message, + }, + }) + } else { + json!({ + "result": { + "code": self.code, + "state":self.sub_code, + "message": self.message, + }, + "response": self.data + }) + } + } +} + +impl FluentJsonData for FluentMessage { + fn set_data(&self, json_data: JsonData, _: &FluentBundle) -> JsonData { + json_data + } +} + +impl FluentJsonData for UserAccountError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500).set_sub_code("user_account"); + match self { + UserAccountError::Param(_) => json_data, + UserAccountError::System(_) => json_data, + UserAccountError::Status(_) => json_data, + UserAccountError::Redis(err) => err.set_data(json_data, fluent), + UserAccountError::RedisPool(err) => err.set_data(json_data, fluent), + UserAccountError::ValidCode(err) => err.set_data(json_data, fluent), + UserAccountError::Sqlx(err) => err.set_data(json_data, fluent), + UserAccountError::Setting(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for ValidCodeError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500); + match self { + ValidCodeError::DelayTimeout(err) => { + json_data.set_sub_code("valid_code").set_data(json!({ + "type":err.prefix + })) + } + ValidCodeError::NotMatch(err) => json_data.set_sub_code("valid_code").set_data(json!({ + "type":err.prefix + })), + ValidCodeError::Utf8Err(_) => json_data.set_sub_code("valid_code_err"), + ValidCodeError::Tag(_) => json_data.set_sub_code("valid_code_err"), + // ValidCodeError::Create(err) => json_data.set_message(fluent.format_message(&err.into())), + ValidCodeError::Redis(err) => err.set_data(json_data, fluent), + ValidCodeError::RedisPool(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for UserAuthError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500); + match self { + UserAuthError::PasswordNotMatch((_, _)) => json_data.set_sub_code("password_wrong"), + UserAuthError::PasswordNotSet(_) => json_data.set_sub_code("password_empty"), + UserAuthError::StatusError(_) => json_data.set_sub_code("status_wrong"), + UserAuthError::UserNotFind(_) => json_data.set_sub_code("not_find"), + UserAuthError::NotLogin(_) => json_data.set_sub_code("not_login"), + UserAuthError::System(_) => json_data.set_sub_code("auth"), + UserAuthError::CheckCaptchaNeed(_) => json_data.set_sub_code("need_captcha"), + UserAuthError::CheckUserLock(_) => json_data.set_sub_code("user_lock"), + UserAuthError::TokenParse(_) => json_data.set_sub_code("token_wrong"), + UserAuthError::Sqlx(err) => err.set_data(json_data, fluent), + UserAuthError::UserAccount(err) => err.set_data(json_data, fluent), + UserAuthError::ValidCode(err) => err.set_data(json_data, fluent), + UserAuthError::Redis(err) => err.set_data(json_data, fluent), + UserAuthError::RedisPool(err) => err.set_data(json_data, fluent), + UserAuthError::SerdeJson(err) => err.set_data(json_data, fluent), + UserAuthError::Utf8Err(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for UserRbacError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_sub_code("rbac").set_code(500); + match self { + UserRbacError::Sqlx(err) => err.set_data(json_data, fluent), + UserRbacError::NotLogin(_) => json_data.set_code(403).set_sub_code("not_login"), + UserRbacError::Check(err) => { + let mut hash = HashMap::<&String, Vec>::new(); + for (k, v) in err { + hash.entry(k).or_default().push(fluent.format_message(v)); + } + json_data + .set_code(403) + .set_sub_code("check_fail") + .set_data(json!( { + "check_detail":hash, + })) + } + UserRbacError::System(_) => json_data, + } + } +} + +impl FluentJsonData for SettingError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500).set_sub_code("setting"); + match self { + SettingError::Sqlx(err) => err.set_data(json_data, fluent), + SettingError::SerdeJson(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for SenderError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500).set_sub_code("sender"); + match self { + SenderError::Sqlx(err) => err.set_data(json_data, fluent), + SenderError::Redis(err) => err.set_data(json_data, fluent), + SenderError::RedisPool(err) => err.set_data(json_data, fluent), + SenderError::Tera(err) => err.set_data(json_data, fluent), + SenderError::Setting(err) => err.set_data(json_data, fluent), + SenderError::System(_) => json_data, + } + } +} + +impl FluentJsonData for AppsError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500).set_sub_code("apps"); + match self { + AppsError::ScopeNotFind(_) => json_data.set_sub_code("app-bad-scope"), + AppsError::System(_) => json_data, + AppsError::Sqlx(err) => err.set_data(json_data, fluent), + AppsError::Redis(err) => err.set_data(json_data, fluent), + AppsError::RedisPool(err) => err.set_data(json_data, fluent), + AppsError::UserAccount(err) => err.set_data(json_data, fluent), + AppsError::SerdeJson(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for ConfigError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500).set_sub_code("config"); + match self { + ConfigError::Io(err) => err.set_data(json_data, fluent), + ConfigError::Config(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for NotifyError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + match self { + NotifyError::Sqlx(err) => err.set_data(json_data, fluent), + NotifyError::Redis(err) => err.set_data(json_data, fluent), + NotifyError::RedisPool(err) => err.set_data(json_data, fluent), + NotifyError::System(_) => json_data.set_code(500).set_sub_code("notify"), + } + } +} + +impl FluentJsonData for GitDocError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + let json_data = json_data.set_code(500).set_sub_code("doc"); + match self { + GitDocError::Sqlx(err) => err.set_data(json_data, fluent), + GitDocError::Git(err) => err.set_data(json_data, fluent), + GitDocError::System(_) => json_data, + GitDocError::Remote(_) => json_data, + } + } +} + +impl FluentJsonData for LoggerError { + fn set_data(&self, json_data: JsonData, fluent: &FluentBundle) -> JsonData { + match self { + LoggerError::Sqlx(err) => err.set_data(json_data, fluent), + } + } +} + +impl FluentJsonData for area_db::AreaError { + fn set_data(&self, json_data: JsonData, _: &FluentBundle) -> JsonData { + match self { + area_db::AreaError::DB(_) => json_data.set_code(500).set_sub_code("area_db"), + area_db::AreaError::System(_) => json_data.set_code(500).set_sub_code("area"), + area_db::AreaError::NotFind(_) => json_data.set_sub_code("not_found"), + area_db::AreaError::Store(_) => json_data.set_sub_code("area_store"), + area_db::AreaError::Tantivy(_) => json_data.set_sub_code("area_tantivy"), + } + } +} + +//lib error + +impl FluentJsonData for sqlx::Error { + fn set_data(&self, json_data: JsonData, _: &FluentBundle) -> JsonData { + match self { + sqlx::Error::RowNotFound => json_data.set_sub_code("not_found").set_code(404), + _ => json_data.set_code(500).set_sub_code("sqlx"), + } + } +} +macro_rules! crate_error_fluent { + ($crate_error:ty,$code:literal) => { + impl FluentJsonData for $crate_error { + fn set_data(&self, json_data: JsonData, _: &FluentBundle) -> JsonData { + json_data.set_code(500).set_sub_code($code) + } + } + }; +} +crate_error_fluent!(config::ConfigError, "config"); +crate_error_fluent!(std::io::Error, "io"); +crate_error_fluent!(tera::Error, "tera"); +crate_error_fluent!(lsys_docs::GitError, "git"); +crate_error_fluent!(redis::RedisError, "redis"); +crate_error_fluent!(deadpool_redis::PoolError, "redis"); +crate_error_fluent!(serde_json::Error, "serde"); +crate_error_fluent!(ParseIntError, "parse"); +crate_error_fluent!(std::string::FromUtf8Error, "parse"); diff --git a/server/lsys-web/src/utils/mod.rs b/server/lsys-web/src/common/mod.rs similarity index 100% rename from server/lsys-web/src/utils/mod.rs rename to server/lsys-web/src/common/mod.rs diff --git a/server/lsys-web/src/utils/param.rs b/server/lsys-web/src/common/param.rs similarity index 100% rename from server/lsys-web/src/utils/param.rs rename to server/lsys-web/src/common/param.rs diff --git a/server/lsys-web/src/dao/mailer.rs b/server/lsys-web/src/dao/mailer.rs index 2e5b792..f3ed5d8 100644 --- a/server/lsys-web/src/dao/mailer.rs +++ b/server/lsys-web/src/dao/mailer.rs @@ -1,5 +1,5 @@ use lsys_app::model::AppsModel; -use lsys_core::{fluent_message, AppCore, RequestEnv}; +use lsys_core::{fluent_message, AppCore, IntoFluentMessage, RequestEnv}; use lsys_logger::dao::ChangeLogger; use lsys_sender::{ dao::{MailSender, SenderError, SenderSmtpConfig, SmtpSenderTask}, @@ -80,7 +80,9 @@ impl WebAppMailer { max_try_num: &Option, env_data: Option<&RequestEnv>, ) -> Result { - check_email(to).map_err(|e| SenderError::System(fluent_message!("mail-send-check", e)))?; + check_email(to).map_err(|e| { + SenderError::System(fluent_message!("mail-send-check", e.to_fluent_message())) + })?; let mut out = self .mailer .send( @@ -144,14 +146,15 @@ impl WebAppMailer { env_data: Option<&RequestEnv>, ) -> Result, SenderError> { for tmp in to.iter() { - check_email(tmp) - .map_err(|e| SenderError::System(fluent_message!("mail-send-check", e)))?; + check_email(tmp).map_err(|e| { + SenderError::System(fluent_message!("mail-send-check", e.to_fluent_message())) + })?; } if let Some(ref cr) = reply { if !cr.is_empty() { check_email(cr).map_err(|e| { SenderError::System(fluent_message!("mail-send-reply-check",{ - "msg":e, + "msg":e.to_fluent_message(), "reply":cr })) })?; diff --git a/server/lsys-web/src/dao/mod.rs b/server/lsys-web/src/dao/mod.rs index 2ac7fd4..f68daf6 100644 --- a/server/lsys-web/src/dao/mod.rs +++ b/server/lsys-web/src/dao/mod.rs @@ -2,7 +2,7 @@ use area_db::AreaDao; use ip2location::LocationDB; use lsys_app::dao::AppDao; use lsys_core::cache::{LocalCacheClear, LocalCacheClearItem}; -use lsys_core::{AppCore, AppCoreError, FluentMgr, RemoteNotify}; +use lsys_core::{AppCore, AppCoreError, FluentMgr, IntoFluentMessage, RemoteNotify}; use lsys_docs::dao::{DocsDao, GitRemoteTask}; use lsys_logger::dao::ChangeLogger; use lsys_notify::dao::Notify; @@ -117,7 +117,10 @@ impl WebDao { } }, Err(err) => { - info!("ip city db not config:{}", err); + info!( + "ip city db not config:{}", + err.to_fluent_message().default_format() + ); } } @@ -177,7 +180,10 @@ impl WebDao { let mail_task = mailer.clone(); tokio::spawn(async move { if let Err(err) = mail_task.task_sender().await { - error!("mailer task error:{}", err.to_string()) + error!( + "mailer task error:{}", + err.to_fluent_message().default_format() + ) } }); let mail_wait = mailer.clone(); @@ -199,7 +205,10 @@ impl WebDao { let notify_task = notify.clone(); tokio::spawn(async move { if let Err(err) = notify_task.task().await { - error!("smser sender error:{}", err.to_string()) + error!( + "smser sender error:{}", + err.to_fluent_message().default_format() + ) } }); @@ -219,14 +228,20 @@ impl WebDao { let sms_task_sender = web_smser.clone(); tokio::spawn(async move { if let Err(err) = sms_task_sender.task_sender().await { - error!("smser sender error:{}", err.to_string()) + error!( + "smser sender error:{}", + err.to_fluent_message().default_format() + ) } }); //启动短信状态查询任务 let sms_task_notify = web_smser.clone(); tokio::spawn(async move { if let Err(err) = sms_task_notify.task_status_query().await { - error!("smser notify error:{}", err.to_string()) + error!( + "smser notify error:{}", + err.to_fluent_message().default_format() + ) } }); @@ -292,7 +307,10 @@ impl WebDao { } } Err(err) => { - error!("load area data fail:{}", err.to_string()) + error!( + "load area data fail:{}", + err.to_fluent_message().default_format() + ) } } Ok(WebDao { diff --git a/server/lsys-web/src/dao/request.rs b/server/lsys-web/src/dao/request.rs index 77626a4..216d9a1 100644 --- a/server/lsys-web/src/dao/request.rs +++ b/server/lsys-web/src/dao/request.rs @@ -1,7 +1,7 @@ use std::{ops::Deref, sync::Arc}; use lsys_app::dao::session::{RestAuthData, RestAuthSession, RestAuthTokenData}; -use lsys_core::{FluentBundle, RequestEnv}; +use lsys_core::{FluentBundle, IntoFluentMessage, RequestEnv}; use lsys_user::dao::auth::{ SessionData, SessionToken, SessionTokenData, UserAuthData, UserAuthRedisStore, UserAuthSession, UserAuthTokenData, UserSession, @@ -26,7 +26,7 @@ impl RequestDao { req_env, } } - pub fn fluent_json_data(&self, data: F) -> JsonData { + pub fn fluent_json_data(&self, data: F) -> JsonData { JsonData::fluent_from(&self.fluent, data) } pub fn fluent_string(&self, data: F) -> String { @@ -80,7 +80,10 @@ impl> RequestAuthDao { - warn!("check user auth error:{}", e); + warn!( + "check user auth error:{}", + e.to_fluent_message().default_format() + ); } } } else { diff --git a/server/lsys-web/src/dao/smser.rs b/server/lsys-web/src/dao/smser.rs index e8cb078..a91592d 100644 --- a/server/lsys-web/src/dao/smser.rs +++ b/server/lsys-web/src/dao/smser.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, sync::Arc}; use lsys_app::model::AppsModel; -use lsys_core::{fluent_message, AppCore, RequestEnv}; +use lsys_core::{fluent_message, AppCore, IntoFluentMessage, RequestEnv}; use lsys_logger::dao::ChangeLogger; use lsys_notify::dao::Notify; use lsys_sender::{ @@ -126,7 +126,7 @@ impl WebAppSmser { check_mobile(tmp.0, tmp.1).map_err(|e| { SenderError::System(fluent_message!("sms-send-check",{ "mobile":tmp.1, - "msg":e + "msg":e.to_fluent_message() })) })?; } @@ -181,7 +181,7 @@ impl WebAppSmser { check_mobile(area, mobile).map_err(|e| { SenderError::System(fluent_message!("sms-send-check",{ "mobile":mobile, - "msg":e + "msg":e.to_fluent_message() })) })?; let mut out = self diff --git a/server/lsys-web/src/dao/user/login.rs b/server/lsys-web/src/dao/user/login.rs index f4f88f1..c7cb4fd 100644 --- a/server/lsys-web/src/dao/user/login.rs +++ b/server/lsys-web/src/dao/user/login.rs @@ -1,6 +1,6 @@ use std::net::IpAddr; -use lsys_core::RequestEnv; +use lsys_core::{IntoFluentMessage, RequestEnv}; use lsys_user::dao::auth::{ LoginEnv, LoginParam, UserAuthError, UserAuthResult, UserAuthSession, UserAuthStore, UserAuthTokenData, UserSession, @@ -43,7 +43,7 @@ impl WebUser { { tracing::warn!( "clear login captcha fail:{} in [{}]", - captcha_err, + captcha_err.to_fluent_message().default_format(), ¶m.show_name() ); } diff --git a/server/lsys-web/src/handler/app/mailer.rs b/server/lsys-web/src/handler/app/mailer.rs index 836ad6e..d925ac2 100644 --- a/server/lsys-web/src/handler/app/mailer.rs +++ b/server/lsys-web/src/handler/app/mailer.rs @@ -2,7 +2,8 @@ use std::collections::HashMap; use crate::{dao::RequestDao, handler::access::AccessAppSenderDoMail, JsonData, JsonResult}; use lsys_app::model::AppsModel; -use lsys_core::{str_time, FluentMessage}; + +use lsys_core::{str_time, IntoFluentMessage}; use serde::Deserialize; use serde_json::{json, Value}; @@ -41,7 +42,7 @@ pub async fn mail_send( } else { Some( str_time(&t) - .map_err(|e| req_dao.fluent_json_data(FluentMessage::from(e)))? + .map_err(|e| req_dao.fluent_json_data(e))? .timestamp() as u64, ) } @@ -121,7 +122,7 @@ pub async fn mail_cancel( "id":e.0.to_string(), "status":!e.1&&e.2.is_none(), // "sending":e.1, - "msg":e.2.map(|e|e.to_string()) + "msg":e.2.map(|e|e.to_fluent_message().default_format()) }) }) .collect::>(); diff --git a/server/lsys-web/src/handler/app/smser.rs b/server/lsys-web/src/handler/app/smser.rs index 8671c9b..36cced3 100644 --- a/server/lsys-web/src/handler/app/smser.rs +++ b/server/lsys-web/src/handler/app/smser.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use crate::{dao::RequestDao, handler::access::AccessAppSenderDoSms, JsonData, JsonResult}; use lsys_app::model::AppsModel; -use lsys_core::{str_time, FluentMessage}; +use lsys_core::{str_time, IntoFluentMessage}; use serde::Deserialize; use serde_json::{json, Value}; @@ -41,7 +41,7 @@ pub async fn sms_send( } else { Some( str_time(&t) - .map_err(|e| req_dao.fluent_json_data(FluentMessage::from(e)))? + .map_err(|e| req_dao.fluent_json_data(e))? .timestamp() as u64, ) } @@ -119,7 +119,7 @@ pub async fn sms_cancel( "id":e.0.to_string(), "status":!e.1&&e.2.is_none(), // "sending":e.1, - "msg":e.2.map(|e|e.to_string()) + "msg":e.2.map(|e|e.to_fluent_message().default_format()) }) }) .collect::>(); diff --git a/server/lsys-web/src/handler/common/rbac/mod.rs b/server/lsys-web/src/handler/common/rbac/mod.rs index 31db9a1..0f7217a 100644 --- a/server/lsys-web/src/handler/common/rbac/mod.rs +++ b/server/lsys-web/src/handler/common/rbac/mod.rs @@ -87,6 +87,6 @@ pub(crate) async fn access_check( ); Err(UserRbacError::System(fluent_message!("rbac-unkown-res",{ - "res":check_res.name + "res":&check_res.name }))) } diff --git a/server/lsys-web/src/handler/common/sender/mailer.rs b/server/lsys-web/src/handler/common/sender/mailer.rs index 350c138..72485b6 100644 --- a/server/lsys-web/src/handler/common/sender/mailer.rs +++ b/server/lsys-web/src/handler/common/sender/mailer.rs @@ -7,7 +7,7 @@ use crate::{ LimitParam, PageParam, {JsonData, JsonResult}, }; use lsys_core::{fluent_message, str_time}; -use lsys_core::{now_time, FluentMessage}; +use lsys_core::{now_time}; use lsys_sender::{ // dao::SenderError, dao::SenderError, @@ -629,7 +629,7 @@ pub async fn mailer_message_send String; -} - -impl FluentFormat for UserAccountError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - UserAccountError::System(err) => fluent.format_message(err), - UserAccountError::Status((_, err)) => fluent.format_message(err), - UserAccountError::Param(err) => fluent.format_message(err), - UserAccountError::Redis(err) => err.fluent_format(fluent), - UserAccountError::RedisPool(err) => err.fluent_format(fluent), - UserAccountError::ValidCode(err) => err.fluent_format(fluent), - UserAccountError::Sqlx(err) => err.fluent_format(fluent), - UserAccountError::Setting(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for FluentMessage { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - fluent.format_message(self) - } -} - -impl FluentFormat for ValidCodeError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - ValidCodeError::Utf8Err(err) => fluent.format_message(err), - ValidCodeError::Tag(err) => fluent.format_message(err), - ValidCodeError::DelayTimeout(err) => err.fluent_format(fluent), - ValidCodeError::NotMatch(err) => err.fluent_format(fluent), - ValidCodeError::Redis(err) => err.fluent_format(fluent), - ValidCodeError::RedisPool(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for UserAuthError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - UserAuthError::PasswordNotMatch((_, err)) => fluent.format_message(err), - UserAuthError::PasswordNotSet((_, err)) => fluent.format_message(err), - UserAuthError::StatusError((_, err)) => fluent.format_message(err), - UserAuthError::UserNotFind(err) => fluent.format_message(err), - UserAuthError::NotLogin(err) => fluent.format_message(err), - UserAuthError::System(err) => fluent.format_message(err), - UserAuthError::CheckUserLock((_, err)) => fluent.format_message(err), - UserAuthError::TokenParse(err) => fluent.format_message(err), - UserAuthError::CheckCaptchaNeed(err) => fluent.format_message(err), - UserAuthError::Sqlx(err) => err.fluent_format(fluent), - UserAuthError::UserAccount(err) => err.fluent_format(fluent), - UserAuthError::ValidCode(err) => err.fluent_format(fluent), - UserAuthError::Redis(err) => err.fluent_format(fluent), - UserAuthError::RedisPool(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for UserRbacError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - UserRbacError::Sqlx(err) => err.fluent_format(fluent), - UserRbacError::NotLogin(err) => fluent.format_message(err), - UserRbacError::Check(_) => fluent.format_message(&fluent_message!("rbac-check-fail")), - UserRbacError::System(err) => fluent.format_message(err), - } - } -} - -impl FluentFormat for SettingError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - SettingError::Sqlx(err) => err.fluent_format(fluent), - SettingError::SerdeJson(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for SenderError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - SenderError::Sqlx(err) => err.fluent_format(fluent), - SenderError::Redis(err) => err.fluent_format(fluent), - SenderError::RedisPool(err) => err.fluent_format(fluent), - SenderError::Tera(err) => err.fluent_format(fluent), - SenderError::System(err) => fluent.format_message(err), - SenderError::Setting(err) => err.fluent_format(fluent), - } - } -} -impl FluentFormat for ValidCodeCheckError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - fluent.format_message(&self.message) - } -} - -impl FluentFormat for AppsError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - AppsError::Sqlx(err) => err.fluent_format(fluent), - AppsError::System(err) => fluent.format_message(err), - AppsError::Redis(err) => err.fluent_format(fluent), - AppsError::RedisPool(err) => err.fluent_format(fluent), - AppsError::ScopeNotFind(err) => fluent.format_message(err), - AppsError::UserAccount(err) => err.fluent_format(fluent), - AppsError::SerdeJson(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for ConfigError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - ConfigError::Io(err) => err.fluent_format(fluent), - ConfigError::Config(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for NotifyError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - NotifyError::Sqlx(err) => err.fluent_format(fluent), - NotifyError::Redis(err) => err.fluent_format(fluent), - NotifyError::RedisPool(err) => err.fluent_format(fluent), - NotifyError::System(err) => fluent.format_message(err), - } - } -} - -impl FluentFormat for GitDocError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - GitDocError::Sqlx(err) => err.fluent_format(fluent), - GitDocError::System(err) => fluent.format_message(err), - GitDocError::Remote(err) => fluent.format_message(err), - GitDocError::Git(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for LoggerError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - LoggerError::Sqlx(err) => err.fluent_format(fluent), - } - } -} - -impl FluentFormat for area_db::AreaError { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - area_db::AreaError::DB(err) => fluent.format_message(&err.into()), - area_db::AreaError::System(err) => fluent.format_message(&err.into()), - area_db::AreaError::NotFind(_) => fluent.format_message(&"not find area record".into()), - area_db::AreaError::Store(e) => { - fluent.format_message(&format!("index area data fail:{}", e).into()) - } - area_db::AreaError::Tantivy(e) => { - fluent.format_message(&format!("tantivy area data fail:{}", e).into()) - } - } - } -} - -//lib error - -impl FluentFormat for sqlx::Error { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - match self { - sqlx::Error::RowNotFound => { - fluent.format_message(&fluent_message!("system-not-found", self)) - } - _ => fluent.format_message(&self.to_string().into()), - } - } -} -macro_rules! crate_error_fluent { - ($crate_error:ty) => { - impl FluentFormat for $crate_error { - fn fluent_format(&self, fluent: &FluentBundle) -> String { - fluent.format_message(&self.to_string().into()) - } - } - }; -} -crate_error_fluent!(config::ConfigError); -crate_error_fluent!(std::io::Error); -crate_error_fluent!(tera::Error); -crate_error_fluent!(lsys_docs::gitError); -crate_error_fluent!(redis::RedisError); -crate_error_fluent!(deadpool_redis::PoolError); -crate_error_fluent!(serde_json::Error); -crate_error_fluent!(ParseIntError); diff --git a/server/lsys-web/src/utils/json_result.rs b/server/lsys-web/src/utils/json_result.rs deleted file mode 100644 index 86274b7..0000000 --- a/server/lsys-web/src/utils/json_result.rs +++ /dev/null @@ -1,355 +0,0 @@ -use lsys_core::{ConfigError, FluentBundle, FluentMessage, ValidCodeError}; -use lsys_docs::dao::GitDocError; -use lsys_logger::dao::LoggerError; -use lsys_notify::dao::NotifyError; -use lsys_rbac::dao::rbac::UserRbacError; -use lsys_sender::dao::SenderError; -use lsys_setting::dao::SettingError; -use lsys_user::dao::{account::UserAccountError, auth::UserAuthError}; -use serde_json::{json, Value}; - -use std::{collections::HashMap, num::ParseIntError}; - -use crate::FluentFormat; -use lsys_app::dao::AppsError; - -pub trait FluentJsonData { - fn json_data(&self, fluent: &FluentBundle) -> JsonData; -} - -pub type JsonResult = Result; - -#[derive(Debug, Clone)] -pub struct JsonData { - code: String, - sub_code: String, - message: String, - data: Option, -} -impl Default for JsonData { - fn default() -> Self { - JsonData { - code: "200".to_string(), - sub_code: "ok".to_string(), - message: "ok".to_string(), - data: None, - } - } -} -impl JsonData { - pub fn fluent_from(fluent: &FluentBundle, data: T) -> JsonData { - data.json_data(fluent) - } - pub fn data(value: Value) -> Self { - JsonData::default().set_message("ok").set_data(value) - } - pub fn error(error: T) -> Self { - JsonData::message_error(format!("error:{}", error)) - } - pub fn message_error(msg: T) -> Self { - JsonData::message(msg).set_code(500).set_sub_code("system") - } - pub fn message(msg: T) -> Self { - JsonData::default().set_message(msg) - } - pub fn set_data(mut self, value: Value) -> Self { - self.data = Some(value); - self - } - pub fn set_total_data(mut self, value: Value, total: T) -> Self { - self.data = Some(json!({ - "total":total.to_string(), - "data":value, - })); - self - } - pub fn set_code(mut self, code: T) -> Self { - self.code = code.to_string(); - self - } - pub fn set_sub_code(mut self, sub_code: T) -> Self { - self.sub_code = sub_code.to_string(); - self - } - pub fn set_message(mut self, msg: T) -> Self { - self.message = msg.to_string(); - self - } - pub fn to_value(&self) -> Value { - if self.data.is_none() { - json!({ - "result": { - "code": self.code, - "state":self.sub_code, - "message": self.message, - }, - }) - } else { - json!({ - "result": { - "code": self.code, - "state":self.sub_code, - "message": self.message, - }, - "response": self.data - }) - } - } -} - -impl FluentJsonData for FluentMessage { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - JsonData::default() - .set_sub_code("system") - .set_message(self.fluent_format(fluent)) - } -} - -impl FluentJsonData for UserAccountError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default().set_sub_code("valid_code"); - match self { - UserAccountError::Param(_) => out.set_message(self.fluent_format(fluent)), - UserAccountError::System(_) => out.set_message(self.fluent_format(fluent)), - UserAccountError::Status(_) => out.set_message(self.fluent_format(fluent)), - UserAccountError::Redis(err) => err.json_data(fluent), - UserAccountError::RedisPool(err) => err.json_data(fluent), - UserAccountError::ValidCode(err) => err.json_data(fluent), - UserAccountError::Sqlx(err) => err.json_data(fluent), - UserAccountError::Setting(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for ValidCodeError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default().set_sub_code("valid_code"); - match self { - ValidCodeError::DelayTimeout(err) => out - .set_data(json!({ - "type":err.prefix - })) - .set_message(self.fluent_format(fluent)), - ValidCodeError::NotMatch(err) => out - .set_data(json!({ - "type":err.prefix - })) - .set_message(self.fluent_format(fluent)), - ValidCodeError::Utf8Err(_) => out.set_message(self.fluent_format(fluent)), - ValidCodeError::Tag(_) => out.set_message(self.fluent_format(fluent)), - // ValidCodeError::Create(err) => out.set_message(fluent.format_message(&err.into())), - ValidCodeError::Redis(err) => err.json_data(fluent), - ValidCodeError::RedisPool(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for UserAuthError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default(); - match self { - UserAuthError::PasswordNotMatch((_, _)) => out - .set_sub_code("password_wrong") - .set_message(self.fluent_format(fluent)), - UserAuthError::PasswordNotSet(_) => out - .set_sub_code("password_empty") - .set_message(self.fluent_format(fluent)), - UserAuthError::StatusError(_) => out - .set_sub_code("status_wrong") - .set_message(self.fluent_format(fluent)), - UserAuthError::UserNotFind(_) => out - .set_sub_code("not_find") - .set_message(self.fluent_format(fluent)), - UserAuthError::NotLogin(_) => out - .set_sub_code("not_login") - .set_message(self.fluent_format(fluent)), - UserAuthError::System(_) => out - .set_code(500) - .set_sub_code("system") - .set_message(self.fluent_format(fluent)), - UserAuthError::CheckCaptchaNeed(_) => out - .set_sub_code("need_captcha") - .set_message(self.fluent_format(fluent)), - UserAuthError::CheckUserLock(_) => out - .set_sub_code("user_lock") - .set_message(self.fluent_format(fluent)), - UserAuthError::TokenParse(_) => out - .set_sub_code("token_wrong") - .set_message(self.fluent_format(fluent)), - UserAuthError::Sqlx(err) => err.json_data(fluent), - UserAuthError::UserAccount(err) => err.json_data(fluent), - UserAuthError::ValidCode(err) => err.json_data(fluent), - UserAuthError::Redis(err) => err.json_data(fluent), - UserAuthError::RedisPool(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for UserRbacError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default().set_sub_code("rbac"); - match self { - UserRbacError::Sqlx(err) => err.json_data(fluent), - UserRbacError::NotLogin(_) => out - .set_sub_code("not_login") - .set_message(self.fluent_format(fluent)), - UserRbacError::Check(err) => { - let mut hash = HashMap::<&String, Vec>::new(); - for (k, v) in err { - hash.entry(k).or_default().push(fluent.format_message(v)); - } - out.set_sub_code("check_fail") - .set_data(json!( { - "check_detail":hash, - })) - .set_message(self.fluent_format(fluent)) - } - UserRbacError::System(_) => out.set_message(self.fluent_format(fluent)), - } - } -} - -impl FluentJsonData for SettingError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - match self { - SettingError::Sqlx(err) => err.json_data(fluent), - SettingError::SerdeJson(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for SenderError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default().set_code(500).set_sub_code("sender"); - match self { - SenderError::Sqlx(err) => err.json_data(fluent), - SenderError::Redis(err) => err.json_data(fluent), - SenderError::RedisPool(err) => err.json_data(fluent), - SenderError::Tera(err) => err.json_data(fluent), - SenderError::Setting(err) => err.json_data(fluent), - SenderError::System(_) => out.set_message(self.fluent_format(fluent)), - } - } -} - -impl FluentJsonData for AppsError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default().set_code(500).set_sub_code("app"); - match self { - AppsError::ScopeNotFind(_) => out - .set_sub_code("app-bad-scope") - .set_message(self.fluent_format(fluent)), - AppsError::System(_) => out.set_message(self.fluent_format(fluent)), - AppsError::Sqlx(err) => err.json_data(fluent), - AppsError::Redis(err) => err.json_data(fluent), - AppsError::RedisPool(err) => err.json_data(fluent), - AppsError::UserAccount(err) => err.json_data(fluent), - AppsError::SerdeJson(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for ConfigError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - match self { - ConfigError::Io(err) => err.json_data(fluent), - ConfigError::Config(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for NotifyError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - match self { - NotifyError::Sqlx(err) => err.json_data(fluent), - NotifyError::Redis(err) => err.json_data(fluent), - NotifyError::RedisPool(err) => err.json_data(fluent), - NotifyError::System(_) => JsonData::default() - .set_code(500) - .set_sub_code("notify") - .set_message(self.fluent_format(fluent)), - } - } -} - -impl FluentJsonData for GitDocError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - match self { - GitDocError::Sqlx(err) => err.json_data(fluent), - GitDocError::Git(err) => err.json_data(fluent), - GitDocError::System(_) => JsonData::default() - .set_sub_code("doc") - .set_code(200) - .set_message(self.fluent_format(fluent)), - GitDocError::Remote(_) => JsonData::default() - .set_sub_code("doc") - .set_code(200) - .set_message(self.fluent_format(fluent)), - } - } -} - -impl FluentJsonData for LoggerError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - match self { - LoggerError::Sqlx(err) => err.json_data(fluent), - } - } -} - -impl FluentJsonData for area_db::AreaError { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - match self { - area_db::AreaError::DB(_) => JsonData::default() - .set_code(500) - .set_sub_code("area") - .set_message(self.fluent_format(fluent)), - area_db::AreaError::System(_) => JsonData::default() - .set_code(500) - .set_sub_code("area") - .set_message(self.fluent_format(fluent)), - area_db::AreaError::NotFind(_) => JsonData::default() - .set_sub_code("not_found") - .set_message(self.fluent_format(fluent)), - area_db::AreaError::Store(_) => JsonData::default() - .set_sub_code("area") - .set_message(self.fluent_format(fluent)), - area_db::AreaError::Tantivy(_) => JsonData::default() - .set_sub_code("tantivy") - .set_message(self.fluent_format(fluent)), - } - } -} - -//lib error - -impl FluentJsonData for sqlx::Error { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - let out = JsonData::default().set_code(500); - match self { - sqlx::Error::RowNotFound => out.set_sub_code("not_found").set_code(404), - _ => out.set_sub_code("sqlx"), - } - .set_message(self.fluent_format(fluent)) - } -} -macro_rules! crate_error_fluent { - ($crate_error:ty,$code:literal) => { - impl FluentJsonData for $crate_error { - fn json_data(&self, fluent: &FluentBundle) -> JsonData { - JsonData::default() - .set_code(500) - .set_sub_code($code) - .set_message(self.fluent_format(fluent)) - } - } - }; -} -crate_error_fluent!(config::ConfigError, "config"); -crate_error_fluent!(std::io::Error, "io"); -crate_error_fluent!(tera::Error, "tera"); -crate_error_fluent!(lsys_docs::gitError, "git"); -crate_error_fluent!(redis::RedisError, "redis"); -crate_error_fluent!(deadpool_redis::PoolError, "redis"); -crate_error_fluent!(serde_json::Error, "serde"); -crate_error_fluent!(ParseIntError, "parse"); diff --git a/ui/README.md b/ui/README.md index 2805ad0..e54250a 100644 --- a/ui/README.md +++ b/ui/README.md @@ -1,4 +1,4 @@ -### 应用管理ui +### 管理UI安装 > 基于reactjs实现 @@ -19,4 +19,6 @@ cd web/ npm i npm run dev +# npm run build #or build ``` + diff --git a/ui/wap/src/utils/rest.js b/ui/wap/src/utils/rest.js index 433b1fb..1f81778 100644 --- a/ui/wap/src/utils/rest.js +++ b/ui/wap/src/utils/rest.js @@ -54,7 +54,7 @@ export function globalRest(path) { }; -export function fialResult(field, message) { +export function failResult(field, message) { return { status: false, field: field, @@ -69,7 +69,7 @@ export function restResult(res) { } return { ...res.data.result, - ...fialResult(res.data.result.state == "valid_code" ? { + ...failResult(res.data.result.state == "valid_code" ? { captcha: res.data.result.message } : {}, res.data.result.message), is_captcha: res.data.result.state == "need_captcha", diff --git a/ui/web/package.json b/ui/web/package.json index 8437237..64173b2 100644 --- a/ui/web/package.json +++ b/ui/web/package.json @@ -33,15 +33,15 @@ "@emotion/react": "^11.10.5", "@emotion/styled": "^11.10.5", "@mui/icons-material": "^5.10.9", - "@mui/lab": "^5.0.0-alpha.133", "@mui/material": "^5.11.10", "@mui/x-date-pickers": "^5.0.10", + "@mui/x-tree-view": "^6.17.0", "@uiw/react-markdown-preview": "^4.1.13", "@uiw/react-textarea-code-editor": "^1.4.4", - "mermaid": "10.4.0", "axios": "^1.1.3", "dayjs": "^1.11.6", "json-bigint": "^1.0.0", + "mermaid": "10.4.0", "prop-types": "^15.8.1", "qrcode": "^1.5.1", "random-string": "^0.2.0", diff --git a/ui/web/src/page/doc.js b/ui/web/src/page/doc.js index 41c950c..da8188a 100644 --- a/ui/web/src/page/doc.js +++ b/ui/web/src/page/doc.js @@ -1,8 +1,9 @@ import ArticleOutlinedIcon from '@mui/icons-material/ArticleOutlined'; import FolderOpenOutlinedIcon from '@mui/icons-material/FolderOpenOutlined'; import FolderOutlinedIcon from '@mui/icons-material/FolderOutlined'; -import TreeItem, { treeItemClasses } from '@mui/lab/TreeItem'; -import TreeView from '@mui/lab/TreeView'; +import { TreeItem } from '@mui/x-tree-view/TreeItem'; +import { treeItemClasses } from '@mui/x-tree-view/TreeItem'; +import { TreeView } from '@mui/x-tree-view/TreeView'; import { Alert, Box, Grid, Link, Stack } from '@mui/material'; import Typography from '@mui/material/Typography'; import { styled } from '@mui/material/styles'; diff --git a/ui/web/src/rest/access.js b/ui/web/src/rest/access.js index 35cf002..4ad15e8 100644 --- a/ui/web/src/rest/access.js +++ b/ui/web/src/rest/access.js @@ -377,7 +377,7 @@ export async function roleDelete(params, config) { role_id } = params; role_id = parseInt(role_id) - if (isNaN(role_id) || role_id <= 0) return fialResult({ id: "缺少ID" }); + if (isNaN(role_id) || role_id <= 0) return failResult({ id: "缺少ID" }); let param = { role_id: role_id }; diff --git a/ui/web/src/rest/app.js b/ui/web/src/rest/app.js index 539b030..4ffb900 100644 --- a/ui/web/src/rest/app.js +++ b/ui/web/src/rest/app.js @@ -1,4 +1,4 @@ -import { fialResult, restResult, sessionRest } from "../utils/rest"; +import { failResult, restResult, sessionRest } from "../utils/rest"; import { isDomain } from "../utils/utils"; function appRest() { return sessionRest('/api/app') @@ -50,7 +50,7 @@ export async function appAdd(param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await appRest().post("add", { user_id: user_id, @@ -78,7 +78,7 @@ export async function appEdit(param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await appRest().post("edit", { app_id: appid, @@ -90,10 +90,10 @@ export async function appEdit(param, config) { } export async function statusApp(param, config) { - const { appid,status} = param; + const { appid, status } = param; let response = await appRest().post("status", { "app_id": appid, - "status":status + "status": status }, config); return restResult(response) } @@ -125,7 +125,7 @@ export async function resetSecretApp(param, config) { } export async function setSubUser(param, config) { - const { appid,user_id,used } = param; + const { appid, user_id, used } = param; let response = await appRest().post("set_sub_user", { "app_id": parseInt(appid), "user_id": parseInt(user_id), @@ -136,36 +136,36 @@ export async function setSubUser(param, config) { export async function listSubUser(param, config) { - const { appid,user_id, page, page_size } = param; - let params={ + const { appid, user_id, page, page_size } = param; + let params = { "app_id": parseInt(appid), - "count_num":true, + "count_num": true, "page": { page: parseInt(page) >= 0 ? (parseInt(page) + 1) : 1, limit: parseInt(page_size) > 0 ? parseInt(page_size) : 25 } }; - if (user_id>0){ - params.user_id=parseInt(user_id) + if (user_id > 0) { + params.user_id = parseInt(user_id) } let response = await appRest().post("list_sub_user", params, config); return restResult(response) } export async function listSubApp(param, config) { - const { appid,user_id, page, page_size } = param; - let params= { + const { appid, user_id, page, page_size } = param; + let params = { "app_id": parseInt(appid), - "count_num":true, + "count_num": true, "page": { page: parseInt(page) >= 0 ? (parseInt(page) + 1) : 1, limit: parseInt(page_size) > 0 ? parseInt(page_size) : 25 } } - if(user_id>0){ - params.user_id=parseInt(user_id) + if (user_id > 0) { + params.user_id = parseInt(user_id) } - let response = await appRest().post("list_sub_app",params, config); + let response = await appRest().post("list_sub_app", params, config); return restResult(response) } @@ -173,7 +173,7 @@ export async function listParentApp(param, config) { const { appid, page, page_size } = param; let response = await appRest().post("list_parent_app", { "app_id": parseInt(appid), - "count_num":true, + "count_num": true, "page": { page: parseInt(page) >= 0 ? (parseInt(page) + 1) : 1, limit: parseInt(page_size) > 0 ? parseInt(page_size) : 25 @@ -183,16 +183,16 @@ export async function listParentApp(param, config) { } export async function setParentApp(param, config) { - const { appid ,parent_appid,sub_secret} = param; + const { appid, parent_appid, sub_secret } = param; let response = await appRest().post("set_parent_app", { "app_id": parseInt(appid), "parent_app_id": parseInt(parent_appid), - "sub_secret":sub_secret + "sub_secret": sub_secret }, config); return restResult(response) } export async function delParentApp(param, config) { - const { appid ,parent_appid} = param; + const { appid, parent_appid } = param; let response = await appRest().post("del_parent_app", { "app_id": parseInt(appid), "parent_app_id": parseInt(parent_appid), diff --git a/ui/web/src/rest/docs.js b/ui/web/src/rest/docs.js index 10a4e4a..7114d30 100644 --- a/ui/web/src/rest/docs.js +++ b/ui/web/src/rest/docs.js @@ -1,5 +1,5 @@ import config from '../../config.json'; -import { fialResult, globalRest, restResult, sessionRest } from "../utils/rest"; +import { failResult, globalRest, restResult, sessionRest } from "../utils/rest"; function docsRest() { return sessionRest('/api/docs') @@ -24,7 +24,7 @@ export async function docsGitAdd(params, config) { errors.url = "URL请提供git地址"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/git_add`, { name: name, @@ -50,7 +50,7 @@ export async function docsGitEdit(params, config) { errors.url = "请提供URL"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/git_edit`, { id: parseInt(doc_id), @@ -73,7 +73,7 @@ export async function docsDelGit(params, config) { errors.branch = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/git_del`, { id: parseInt(git_id), @@ -94,7 +94,7 @@ export async function docsGitDetail(param, config) { errors.name = "URL请提供git地址"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/git_detail`, { url: url @@ -127,7 +127,7 @@ export async function docsTagAdd(param, config) { errors.version = "请提供正确的版本信息"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_add`, { git_id: git_id, @@ -144,7 +144,7 @@ export async function docsTagDel(param, config) { errors.tag_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_del`, { tag_id: tag_id }, config); return restResult(response) @@ -177,7 +177,7 @@ export async function docsTagCloneDel(param, config) { errors.clone_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_clone_del`, { clone_id: parseInt(clone_id) @@ -192,7 +192,7 @@ export async function docsTagStatusSet(param, config) { errors.tag_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_status`, { tag_id: parseInt(tag_id), @@ -208,7 +208,7 @@ export async function docsTagDir(params, config) { errors.tag_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_dir`, { tag_id: parseInt(tag_id), @@ -223,7 +223,7 @@ export async function docsTagLogs(params, config) { errors.tag_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_logs`, { tag_id: parseInt(tag_id) @@ -240,7 +240,7 @@ export async function docsTagFileData(params, config) { errors.file_path = "请先提供查看路径"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/tag_file_data`, { tag_id: parseInt(tag_id), @@ -255,7 +255,7 @@ export async function docsMenuList(params, config) { errors.tag_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/menu_list`, { tag_id: parseInt(tag_id), @@ -272,7 +272,7 @@ export async function docsMenuAdd(params, config) { errors.menu_path = "请输入目录路径"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/menu_add`, { tag_id: parseInt(tag_id), @@ -287,7 +287,7 @@ export async function docsMenuDel(params, config) { errors.menu_id = "ID异常"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await docsRest().post(`/setting/menu_del`, { menu_id: parseInt(menu_id), diff --git a/ui/web/src/rest/login.js b/ui/web/src/rest/login.js index a3b71dd..647754f 100644 --- a/ui/web/src/rest/login.js +++ b/ui/web/src/rest/login.js @@ -1,5 +1,5 @@ import isEmail from "validator/lib/isEmail"; -import { fialResult, globalRest, restResult, sessionRest } from "../utils/rest"; +import { failResult, globalRest, restResult, sessionRest } from "../utils/rest"; function LoggedRest() { return sessionRest('/api/user') @@ -51,7 +51,7 @@ export async function nameLogin(login_type, param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await LoginRest().post("login/" + login_type, param, config); return restResult(response) @@ -81,7 +81,7 @@ export async function emailLoginSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -119,7 +119,7 @@ export async function emailCodeLogin(param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await LoginRest().post("/login/email-code", param, config); return restResult(response) @@ -149,7 +149,7 @@ export async function emailLogin(param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await LoginRest().post("/login/email-code", param, config); return restResult(response) @@ -181,7 +181,7 @@ export async function mobileCodeLogin(param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await LoginRest().post("/login/sms-code", param, config); return restResult(response) @@ -198,7 +198,7 @@ export async function mobileLoginSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { mobile: mobile, @@ -225,7 +225,7 @@ export async function emailSignupSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -254,7 +254,7 @@ export async function emailSignup(param, config) { errors.name = "邮箱格式错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -277,7 +277,7 @@ export async function mobileSignupSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { mobile: mobile, @@ -310,7 +310,7 @@ export async function mobileSignup(param, config) { errors.name = "手机号格式错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { @@ -335,7 +335,7 @@ export async function emailFindPasswordSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -362,7 +362,7 @@ export async function emailFindPassword(param, config) { errors.password = "密码不能小于6位"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -387,7 +387,7 @@ export async function mobileFindPasswordSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { mobile: mobile, @@ -417,7 +417,7 @@ export async function mobileFindPassword(param, config) { errors.password = "密码不能小于6位"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { mobile: mobile, @@ -451,7 +451,7 @@ export async function QrcodeLogin(login_type, login_state, config) { url = window.location.protocol + "//" + window.location.host + window.location.pathname + "mobile/wechat-login.html"; break default: - return fialResult({}, `绑定类型[${login_type}]不支持`); + return failResult({}, `绑定类型[${login_type}]不支持`); } let response = await LoginRest().post("/external_login_url", { "login_type": login_type, diff --git a/ui/web/src/rest/sender_setting.js b/ui/web/src/rest/sender_setting.js index dd76534..f37e593 100644 --- a/ui/web/src/rest/sender_setting.js +++ b/ui/web/src/rest/sender_setting.js @@ -1,5 +1,5 @@ import isEmail from "validator/lib/isEmail"; -import { fialResult, restResult, sessionRest } from "../utils/rest"; +import { failResult, restResult, sessionRest } from "../utils/rest"; import { isCallbackKey, isDomain } from "../utils/utils"; import dayjs from "dayjs"; @@ -162,7 +162,7 @@ export async function senderAddConfig(type, param, config) { break; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest(type).post("config_add", data, config); return restResult(response) @@ -202,7 +202,7 @@ export async function senderDelConfig(type, param, config) { //message export async function mailListAppMessage(param, config) { - const { app_id, user_id,sn_id, tpl_id, to_mail, status, start_pos, end_pos, page_size } = param; + const { app_id, user_id, sn_id, tpl_id, to_mail, status, start_pos, end_pos, page_size } = param; let data = { count_num: false, limit: { @@ -246,14 +246,14 @@ export async function mailListAppMessage(param, config) { data.to_mail = to_mail; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("mailer").post("/message_list", data, config); return restResult(response, ['not_found']) } export async function smsListAppMessage(param, config) { - const { app_id, user_id,sn_id, tpl_id, mobile, status, start_pos, end_pos, page_size } = param; + const { app_id, user_id, sn_id, tpl_id, mobile, status, start_pos, end_pos, page_size } = param; let data = { count_num: false, limit: { @@ -297,7 +297,7 @@ export async function smsListAppMessage(param, config) { data.mobile = mobile; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/message_list", data, config); return restResult(response, ['not_found']) @@ -323,7 +323,7 @@ export async function senderListAppMessageLog(type, param, config) { export async function senderCancelAppMessage(type, param, config) { const { message_id } = param; if (message_id <= 0) { - return fialResult({ message_id: "缺少ID" }); + return failResult({ message_id: "缺少ID" }); } let response = await senderSettingRest(type).post("/message_cancel", { message_id: message_id.toString(), @@ -334,7 +334,7 @@ export async function senderCancelAppMessage(type, param, config) { export async function senderSeeAppMessage(type, param, config) { const { message_id } = param; if (message_id <= 0) { - return fialResult({ message_id: "缺少ID" }); + return failResult({ message_id: "缺少ID" }); } let response = await senderSettingRest(type).post("/message_body", { message_id: message_id.toString(), @@ -347,10 +347,10 @@ export async function senderSeeAppMessage(type, param, config) { export async function senderSetMessageNotify(type, param, config) { const { url, app_id } = param; if (app_id <= 0) { - return fialResult({ app_id: "缺少ID" }); + return failResult({ app_id: "缺少ID" }); } if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") { - return fialResult({ url: "url错误" }); + return failResult({ url: "url错误" }); } let response = await senderSettingRest(type).post("/notify_set_config", { app_id: parseInt(app_id), @@ -439,7 +439,7 @@ export async function smsListTplConfig(param, config) { data.tpl = tpl; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/tpl_config_list", data, config); return restResult(response, ['not_found']) @@ -473,7 +473,7 @@ export async function smsAppSend(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let sp = { tpl_id: parseInt(tpl_id), @@ -519,7 +519,7 @@ export async function smsAddAliConfig(param, config) { errors.callback_key = "回调KEY错误,只能包含数字字母的字符串"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/ali_config_add", param, config); return restResult(response) @@ -546,7 +546,7 @@ export async function smsEditAliConfig(param, config) { errors.callback_key = "回调KEY错误,只能包含数字字母的字符串"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/ali_config_edit", { ...param, @@ -594,7 +594,7 @@ export async function smsAddAppAliConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/ali_app_config_add", data, config); return restResult(response) @@ -635,7 +635,7 @@ export async function smsAddHwConfig(param, config) { errors.callback_key = "回调KEY错误,只能包含数字字母的字符串"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/hw_config_add", param, config); return restResult(response) @@ -662,7 +662,7 @@ export async function smsEditHwConfig(param, config) { errors.url = "提供URL"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/hw_config_edit", { ...param, @@ -714,7 +714,7 @@ export async function smsAddAppHwConfig(param, config) { errors.sender = "模板通道错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let map_data = (template_map + '').split(","); map_data = map_data.filter((e) => e) @@ -763,7 +763,7 @@ export async function smsAddTenConfig(param, config) { errors.callback_key = "回调KEY错误,只能包含数字字母的字符串"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/ten_config_add", param, config); return restResult(response) @@ -790,7 +790,7 @@ export async function smsEditTenConfig(param, config) { errors.region = "区域不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/ten_config_edit", { ...param, @@ -840,7 +840,7 @@ export async function smsAddAppTenConfig(param, config) { errors.sign_name = "签名必填"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let map_data = (template_map + '').split(","); map_data = map_data.filter((e) => e) @@ -887,7 +887,7 @@ export async function smsAddCloOpenConfig(param, config) { errors.callback_key = "回调KEY错误,只能包含数字字母的字符串"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/cloopen_config_add", param, config); return restResult(response) @@ -913,7 +913,7 @@ export async function smsEditCloOpenConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/cloopen_config_edit", { ...param, @@ -958,7 +958,7 @@ export async function smsAddAppCloOpenConfig(param, config) { if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let map_data = (template_map + '').split(","); map_data = map_data.filter((e) => e) @@ -1005,7 +1005,7 @@ export async function smsAddJdConfig(param, config) { errors.region = "区域不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/jd_config_add", param, config); return restResult(response) @@ -1029,7 +1029,7 @@ export async function smsEditJdConfig(param, config) { errors.region = "区域不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/jd_config_edit", { ...param, @@ -1077,7 +1077,7 @@ export async function smsAddAppJdConfig(param, config) { errors.sign_id = "签名必填"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let map_data = (template_map + '').split(","); map_data = map_data.filter((e) => e) @@ -1117,7 +1117,7 @@ export async function smsAddNeteaseConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/netease_config_add", param, config); return restResult(response) @@ -1139,7 +1139,7 @@ export async function smsEditNeteaseConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("smser").post("/netease_config_edit", { ...param, @@ -1183,7 +1183,7 @@ export async function smsAddAppNeteaseConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let map_data = (template_map + '').split(","); map_data = map_data.filter((e) => e) @@ -1300,7 +1300,7 @@ export async function mailAddSmtpConfig(param, config) { errors.email = "请输入邮箱或留空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("mailer").post("/smtp_config_add", { name: name + '', @@ -1350,7 +1350,7 @@ export async function mailEditSmtpConfig(param, config) { errors.email = "请输入邮箱或留空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("mailer").post("/smtp_config_edit", { name: name + '', @@ -1398,7 +1398,7 @@ export async function mailListTplConfig(param, config) { data.tpl = tpl; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("mailer").post("/tpl_config_list", data, config); return restResult(response, ['not_found']) @@ -1426,7 +1426,7 @@ export async function mailAppSend(param, config) { } } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let sp = { tpl_id: parseInt(tpl_id), @@ -1485,7 +1485,7 @@ export async function mailAddAppSmtpConfig(param, config) { errors.subject_tpl_id = "请选择标题模板"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("mailer").post("/smtp_app_config_add", data, config); return restResult(response) @@ -1514,7 +1514,7 @@ export async function tplsAddConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let data = { @@ -1536,7 +1536,7 @@ export async function tplsEditConfig(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } let response = await senderSettingRest("tpls").post("/edit", { id: parseInt(id), diff --git a/ui/web/src/rest/user.js b/ui/web/src/rest/user.js index 384c1f7..bbb4941 100644 --- a/ui/web/src/rest/user.js +++ b/ui/web/src/rest/user.js @@ -1,5 +1,5 @@ import isEmail from "validator/lib/isEmail"; -import { fialResult, globalRest, restResult, sessionRest } from "../utils/rest"; +import { failResult, globalRest, restResult, sessionRest } from "../utils/rest"; function userRest() { return sessionRest('/api/user') @@ -46,7 +46,7 @@ export async function setInfo(param, config) { errors.gender = "性别选错错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { nikename: nikename, @@ -66,7 +66,7 @@ export async function setUsername(param, config) { errors.name = "登陆名需大于1个字符"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { name: name, @@ -99,7 +99,7 @@ export async function setPassword(param, config) { } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { old_password: old_password, @@ -132,7 +132,7 @@ export async function mobileAdd(param, config) { errors.name = "手机格式错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { area_code: "86", @@ -153,7 +153,7 @@ export async function mobileSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { area_code: "86", @@ -174,7 +174,7 @@ export async function mobileConfirm(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { mobile_id: parseInt(id), @@ -229,7 +229,7 @@ export async function AddressEdit(param, config) { errors.name = "收货名称错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { address_id: id, @@ -261,7 +261,7 @@ export async function AddressAdd(param, config) { errors.name = "收货名称错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { code: code, @@ -306,7 +306,7 @@ export async function emailAdd(param, config) { errors.name = "邮箱格式错误"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -325,7 +325,7 @@ export async function emailSendCode(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email: email, @@ -345,7 +345,7 @@ export async function emailConfirm(param, config) { errors.captcha = "验证码不能为空"; } if (Object.keys(errors).length) { - return fialResult(errors); + return failResult(errors); } var param = { email_id: parseInt(id), @@ -398,7 +398,7 @@ export async function oauthAdd(login_type, login_state, config) { url = window.location.protocol + "//" + window.location.host + window.location.pathname + "mobile/wechat-login.html"; break default: - return fialResult({}, `绑定类型[${login_type}]不支持`); + return failResult({}, `绑定类型[${login_type}]不支持`); } let response = await userRest().post("/external/bind_url", { "login_state": login_state, diff --git a/ui/web/src/utils/rest.js b/ui/web/src/utils/rest.js index b77f558..21c8774 100644 --- a/ui/web/src/utils/rest.js +++ b/ui/web/src/utils/rest.js @@ -104,7 +104,7 @@ export function sessionRest(path) { return ax } -export function fialResult(field, message) { +export function failResult(field, message) { if (!message) { message = Object.values(field).join(";") } @@ -116,41 +116,49 @@ export function fialResult(field, message) { }; export function restResult(res, ignore) { + if (typeof ignore == 'string') { + ignore = [ignore] + } + if (!res?.data?.response) res.data.response = []; if (res?.data?.result?.code != 200) { + + if (ignore && ignore.length > 0 && ignore.includes(res?.data?.result?.state)) { + return { + status: true, + ...res.data.response + }; + } + switch (res?.data?.result?.state) { + case "not_login": + userSessionClear() case "jwt_bad_token": userSessionClear() break } return { ...(res?.data?.result ?? {}), - ...fialResult({}, res?.data?.result?.message ?? "未知错误"), + ...failResult(res?.data?.result?.state == "valid_code" ? { + captcha: res.data.result.message + } : {}, res?.data?.result?.message ?? "未知错误"), + is_captcha: res.data.result.state == "need_captcha", data: res?.data?.response ?? null } } - if (typeof ignore == 'string') { - ignore = [ignore] - } - switch (res.data.result.state) { - case "not_login": - userSessionClear() - default: - if (res.data.result.state == 'ok' || (ignore && ignore.length > 0 && ignore.includes(res.data.result.state))) { - if (!res.data.response) res.data.response = []; - return { - status: true, - ...res.data.response - }; - } - return { - ...res.data.result, - ...fialResult(res.data.result.state == "valid_code" ? { - captcha: res.data.result.message - } : {}, res.data.result.message), - is_captcha: res.data.result.state == "need_captcha", - data: res.data.response - } - } + return { + status: true, + ...res.data.response + }; + + + // return { + // ...res.data.result, + // ...failResult(res.data.result.state == "valid_code" ? { + // captcha: res.data.result.message + // } : {}, res.data.result.message), + // is_captcha: res.data.result.state == "need_captcha", + // data: res.data.response + // } }; export function userSessionGet(session) {