缓存管理
-查看和管理本地缓存文件。
-| 文件名 | 大小 | 操作 | -
|---|
From f5a1407aa3545d8cd433ca23f82edfc01e58afc9 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 8 Apr 2026 17:00:00 +0800 Subject: [PATCH] refactor: update projects and remove legacy components --- .github/pull_request_template.md | 2 +- .github/workflows/docker.yml | 69 +- .gitignore | 1 - Dockerfile | 3 +- app/assets/admin/pages/cache.html | 81 - app/assets/admin/pages/config.html | 43 - app/assets/admin/pages/login.html | 36 - app/assets/admin/pages/token.html | 186 -- app/assets/css/app.css | 579 ------ app/assets/favicon.ico | Bin 15406 -> 0 bytes app/assets/function/pages/chat.html | 155 -- app/assets/function/pages/imagine.html | 247 --- app/assets/function/pages/login.html | 39 - app/assets/function/pages/video.html | 163 -- app/assets/function/pages/voice.html | 108 - app/assets/i18n/README.md | 213 -- app/assets/i18n/i18n.js | 124 -- app/assets/i18n/locales/en.json | 589 ------ app/assets/i18n/locales/zh.json | 589 ------ app/assets/js/admin/cache.js | 109 - app/assets/js/admin/config.js | 257 --- app/assets/js/admin/login.js | 21 - app/assets/js/admin/token.js | 380 ---- app/assets/js/core/auth.js | 129 -- app/assets/js/core/header.js | 76 - app/assets/js/core/sse.js | 27 - app/assets/js/core/toast.js | 23 - app/assets/js/core/ui.js | 111 - app/assets/js/webui/chat.js | 1836 ----------------- app/assets/js/webui/imagine.js | 1304 ------------ app/assets/js/webui/login.js | 25 - app/assets/js/webui/video.js | 707 ------- app/assets/js/webui/voice.js | 96 - app/control/account/__init__.py | 2 + app/control/account/backends/factory.py | 95 +- app/control/account/backends/local.py | 40 +- app/control/account/backends/redis.py | 12 +- app/control/account/backends/sql.py | 14 +- app/control/account/commands.py | 4 +- app/control/account/enums.py | 2 - app/control/account/models.py | 42 +- app/control/account/quota_defaults.py | 93 +- app/control/account/refresh.py | 196 +- app/control/account/repository.py | 2 - app/control/account/runtime.py | 22 + app/control/account/scheduler.py | 68 +- app/control/account/state_machine.py | 2 - app/control/admin/service.py | 88 - app/control/model/enums.py | 10 +- app/control/model/registry.py | 39 +- app/control/model/spec.py | 20 +- app/control/proxy/__init__.py | 61 +- app/control/proxy/feedback.py | 2 - app/control/proxy/models.py | 2 - app/control/proxy/providers/flaresolverr.py | 2 - app/control/proxy/providers/manual.py | 2 - app/control/proxy/scheduler.py | 2 - app/dataplane/account/__init__.py | 36 +- app/dataplane/account/feedback.py | 8 +- app/dataplane/account/lease.py | 2 - app/dataplane/account/selector.py | 13 +- app/dataplane/account/sync.py | 5 +- app/dataplane/account/table.py | 94 +- app/dataplane/proxy/__init__.py | 9 +- app/dataplane/proxy/adapters/headers.py | 4 +- app/dataplane/proxy/adapters/session.py | 7 +- app/dataplane/proxy/selector.py | 2 - app/dataplane/proxy/table.py | 2 - app/dataplane/reverse/classifier.py | 2 - app/dataplane/reverse/executor.py | 4 +- app/dataplane/reverse/feedback.py | 2 - app/dataplane/reverse/planner.py | 14 +- app/dataplane/reverse/protocol/xai_assets.py | 29 +- app/dataplane/reverse/protocol/xai_auth.py | 198 +- app/dataplane/reverse/protocol/xai_chat.py | 409 +++- .../reverse/protocol/xai_chat_reasoning.py | 633 ++++++ app/dataplane/reverse/protocol/xai_image.py | 117 +- .../reverse/protocol/xai_image_edit.py | 107 + app/dataplane/reverse/protocol/xai_livekit.py | 2 - app/dataplane/reverse/protocol/xai_usage.py | 19 +- app/dataplane/reverse/protocol/xai_video.py | 22 +- .../reverse/runtime/endpoint_table.py | 2 - app/dataplane/reverse/runtime/profiles.py | 2 - .../reverse/transport/asset_upload.py | 55 +- app/dataplane/reverse/transport/assets.py | 35 +- app/dataplane/reverse/transport/grpc_web.py | 51 +- app/dataplane/reverse/transport/http.py | 127 +- app/dataplane/reverse/transport/imagine_ws.py | 496 +++-- app/dataplane/reverse/transport/livekit.py | 2 - app/dataplane/reverse/transport/media.py | 6 +- app/dataplane/reverse/transport/websocket.py | 5 +- app/dataplane/reverse/types.py | 20 +- app/dataplane/shared/enums.py | 6 +- app/main.py | 15 +- app/migrations/account_v1_to_v2.py | 2 - app/migrations/runner.py | 2 - app/platform/auth/middleware.py | 13 +- app/platform/config/loader.py | 2 - app/platform/config/snapshot.py | 20 +- app/platform/errors.py | 2 - app/platform/logging/logger.py | 2 - app/platform/meta.py | 29 + app/platform/net/grpc.py | 2 - app/platform/net/http_pool.py | 99 - app/platform/runtime/batch.py | 2 - app/platform/runtime/clock.py | 2 - app/platform/runtime/ids.py | 2 - app/platform/runtime/task.py | 2 - app/platform/storage/__init__.py | 5 + app/platform/storage/contract.py | 2 - app/platform/storage/media_paths.py | 22 + app/platform/storage/revision.py | 2 - app/platform/update_check.py | 159 ++ app/products/admin/__init__.py | 3 - app/products/admin/handlers/__init__.py | 1 - app/products/admin/handlers/batch_ops.py | 181 -- app/products/admin/handlers/batch_stream.py | 66 - app/products/admin/handlers/config.py | 89 - app/products/admin/handlers/diagnostics.py | 29 - app/products/admin/handlers/tokens.py | 185 -- app/products/admin/router.py | 23 - app/products/openai/_format.py | 201 ++ app/products/openai/chat.py | 422 +++- app/products/openai/dto.py | 69 - app/products/openai/image.py | 173 -- app/products/openai/image_edit.py | 310 --- app/products/openai/images.py | 1159 +++++++++++ app/products/openai/response.py | 112 - app/products/openai/responses.py | 466 +++++ app/products/openai/router.py | 292 ++- app/products/openai/schemas.py | 96 + app/products/openai/video.py | 1092 ++++++++-- app/products/web/__init__.py | 6 +- app/products/web/admin/__init__.py | 121 +- app/products/web/admin/assets.py | 143 ++ app/products/web/admin/batch.py | 116 +- .../{admin/handlers => web/admin}/cache.py | 73 +- app/products/web/admin/tokens.py | 202 +- app/products/web/{routes.py => router.py} | 24 +- app/products/web/webui/__init__.py | 16 + app/products/web/webui/chat.py | 47 + app/products/web/webui/imagine.py | 230 +++ app/products/web/webui/pages.py | 43 + app/products/{ => web}/webui/voice.py | 28 +- app/products/webui/__init__.py | 1 - app/products/webui/files.py | 47 - app/products/webui/imagine.py | 389 ---- app/products/webui/pages.py | 96 - app/products/webui/router.py | 19 - app/statics/admin/account.html | 1377 ++++++++++--- app/statics/admin/cache.html | 808 ++++++++ app/statics/admin/config.html | 969 +++++++++ app/statics/admin/header.html | 56 +- app/statics/css/app.css | 881 +++++++- app/statics/i18n/de.json | 522 +++++ app/statics/i18n/en.json | 662 +++++- app/statics/i18n/es.json | 522 +++++ app/statics/i18n/fr.json | 522 +++++ app/statics/i18n/ja.json | 522 +++++ app/statics/i18n/zh.json | 670 +++++- app/statics/js/admin-header.js | 562 ++++- app/statics/js/i18n.js | 76 +- app/statics/js/toast.js | 87 +- app/statics/js/webui-header.js | 195 ++ app/statics/js/webui/chat.js | 1506 ++++++++++++++ app/statics/js/webui/chatkit.js | 514 +++++ app/statics/js/webui/masonry.js | 668 ++++++ app/statics/webui/chat.html | 93 + app/statics/webui/chatkit.html | 123 ++ app/statics/webui/header.html | 59 + app/statics/webui/login.html | 3 - app/statics/webui/masonry.html | 79 + config.defaults.toml | 252 +-- config.toml | 122 -- docker-compose.yml | 19 +- docs/README.en.md | 92 +- main.py | 2 - pyproject.toml | 2 +- readme.md | 36 +- render.yaml | 6 +- scripts/init_storage.sh | 3 +- uv.lock | 2 +- 182 files changed, 18333 insertions(+), 12332 deletions(-) delete mode 100644 app/assets/admin/pages/cache.html delete mode 100644 app/assets/admin/pages/config.html delete mode 100644 app/assets/admin/pages/login.html delete mode 100644 app/assets/admin/pages/token.html delete mode 100644 app/assets/css/app.css delete mode 100644 app/assets/favicon.ico delete mode 100644 app/assets/function/pages/chat.html delete mode 100644 app/assets/function/pages/imagine.html delete mode 100644 app/assets/function/pages/login.html delete mode 100644 app/assets/function/pages/video.html delete mode 100644 app/assets/function/pages/voice.html delete mode 100644 app/assets/i18n/README.md delete mode 100644 app/assets/i18n/i18n.js delete mode 100644 app/assets/i18n/locales/en.json delete mode 100644 app/assets/i18n/locales/zh.json delete mode 100644 app/assets/js/admin/cache.js delete mode 100644 app/assets/js/admin/config.js delete mode 100644 app/assets/js/admin/login.js delete mode 100644 app/assets/js/admin/token.js delete mode 100644 app/assets/js/core/auth.js delete mode 100644 app/assets/js/core/header.js delete mode 100644 app/assets/js/core/sse.js delete mode 100644 app/assets/js/core/toast.js delete mode 100644 app/assets/js/core/ui.js delete mode 100644 app/assets/js/webui/chat.js delete mode 100644 app/assets/js/webui/imagine.js delete mode 100644 app/assets/js/webui/login.js delete mode 100644 app/assets/js/webui/video.js delete mode 100644 app/assets/js/webui/voice.js create mode 100644 app/control/account/runtime.py delete mode 100644 app/control/admin/service.py create mode 100644 app/dataplane/reverse/protocol/xai_chat_reasoning.py create mode 100644 app/dataplane/reverse/protocol/xai_image_edit.py create mode 100644 app/platform/meta.py delete mode 100644 app/platform/net/http_pool.py create mode 100644 app/platform/storage/media_paths.py create mode 100644 app/platform/update_check.py delete mode 100644 app/products/admin/__init__.py delete mode 100644 app/products/admin/handlers/__init__.py delete mode 100644 app/products/admin/handlers/batch_ops.py delete mode 100644 app/products/admin/handlers/batch_stream.py delete mode 100644 app/products/admin/handlers/config.py delete mode 100644 app/products/admin/handlers/diagnostics.py delete mode 100644 app/products/admin/handlers/tokens.py delete mode 100644 app/products/admin/router.py create mode 100644 app/products/openai/_format.py delete mode 100644 app/products/openai/dto.py delete mode 100644 app/products/openai/image.py delete mode 100644 app/products/openai/image_edit.py create mode 100644 app/products/openai/images.py delete mode 100644 app/products/openai/response.py create mode 100644 app/products/openai/responses.py create mode 100644 app/products/openai/schemas.py create mode 100644 app/products/web/admin/assets.py rename app/products/{admin/handlers => web/admin}/cache.py (59%) rename app/products/web/{routes.py => router.py} (69%) create mode 100644 app/products/web/webui/__init__.py create mode 100644 app/products/web/webui/chat.py create mode 100644 app/products/web/webui/imagine.py create mode 100644 app/products/web/webui/pages.py rename app/products/{ => web}/webui/voice.py (66%) delete mode 100644 app/products/webui/__init__.py delete mode 100644 app/products/webui/files.py delete mode 100644 app/products/webui/imagine.py delete mode 100644 app/products/webui/pages.py delete mode 100644 app/products/webui/router.py create mode 100644 app/statics/admin/cache.html create mode 100644 app/statics/admin/config.html create mode 100644 app/statics/i18n/de.json create mode 100644 app/statics/i18n/es.json create mode 100644 app/statics/i18n/fr.json create mode 100644 app/statics/i18n/ja.json create mode 100644 app/statics/js/webui-header.js create mode 100644 app/statics/js/webui/chat.js create mode 100644 app/statics/js/webui/chatkit.js create mode 100644 app/statics/js/webui/masonry.js create mode 100644 app/statics/webui/chat.html create mode 100644 app/statics/webui/chatkit.html create mode 100644 app/statics/webui/header.html create mode 100644 app/statics/webui/masonry.html delete mode 100644 config.toml delete mode 100644 main.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 87b9ecfe..6feaffcb 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -27,7 +27,7 @@ ```text 例如: -- uv run main.py / uv run granian ... 启动正常 +- uv run granian ... app.main:app 启动正常 - 调用 /v1/chat/completions 返回符合预期 ``` diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index aa602991..1c756504 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -21,26 +21,19 @@ jobs: contents: read packages: write id-token: write - - strategy: - fail-fast: false - matrix: - include: - # AMD64 平台 - - platform: linux/amd64 - suffix: amd64 - # ARM64 平台 - - platform: linux/arm64 - suffix: arm64 steps: - name: Checkout repository uses: actions/checkout@v6 + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to Container Registry + if: github.event_name != 'pull_request' uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} @@ -53,57 +46,19 @@ jobs: with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | - # 分支推送 - type=ref,event=branch,suffix=-${{ matrix.suffix }} - # 语义化版本:完整版本号 - type=semver,pattern={{version}},suffix=-${{ matrix.suffix }} - # latest标签 - type=raw,value=latest-${{ matrix.suffix }},enable={{is_default_branch}} + # push main → latest(排除 tag 触发) + type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} + # tag 推送 → 版本号 + type=semver,pattern={{version}} - name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . - platforms: ${{ matrix.platform }} + platforms: linux/amd64,linux/arm64 push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha,scope=${{ matrix.suffix }} - cache-to: type=gha,mode=max,scope=${{ matrix.suffix }} - pull: true - - merge-manifests: - runs-on: ubuntu-latest - needs: build-and-push - if: github.event_name != 'pull_request' - permissions: - contents: read - packages: write - - steps: - - name: Log in to Container Registry - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract metadata - id: meta - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=ref,event=branch - type=semver,pattern={{version}} - type=raw,value=latest,enable={{is_default_branch}} - - - name: Create and push manifest - run: | - TAGS="${{ steps.meta.outputs.tags }}" - for tag in $TAGS; do - echo "合并标签: $tag" - docker buildx imagetools create -t $tag \ - ${tag}-amd64 \ - ${tag}-arm64 - done \ No newline at end of file + cache-from: type=gha + cache-to: type=gha,mode=max + pull: true \ No newline at end of file diff --git a/.gitignore b/.gitignore index 13ea1245..26eec291 100644 --- a/.gitignore +++ b/.gitignore @@ -54,5 +54,4 @@ app/data/ htmlcov/ # Project specific -config.local.toml .ace-tool/ diff --git a/Dockerfile b/Dockerfile index 2aa8c7ec..fe7c0fef 100644 --- a/Dockerfile +++ b/Dockerfile @@ -64,7 +64,6 @@ COPY --from=builder /opt/venv /opt/venv COPY config.defaults.toml ./ COPY app ./app COPY _public ./_public -COPY main.py ./ COPY scripts ./scripts RUN mkdir -p /app/data /app/logs \ @@ -74,4 +73,4 @@ EXPOSE 8000 ENTRYPOINT ["/app/scripts/entrypoint.sh"] -CMD ["sh", "-c", "granian --interface asgi --host ${SERVER_HOST:-0.0.0.0} --port ${SERVER_PORT:-8000} --workers ${SERVER_WORKERS:-1} main:app"] +CMD ["sh", "-c", "granian --interface asgi --host ${SERVER_HOST:-0.0.0.0} --port ${SERVER_PORT:-8000} --workers ${SERVER_WORKERS:-1} app.main:app"] diff --git a/app/assets/admin/pages/cache.html b/app/assets/admin/pages/cache.html deleted file mode 100644 index 16877a5b..00000000 --- a/app/assets/admin/pages/cache.html +++ /dev/null @@ -1,81 +0,0 @@ - - -
- - -查看和管理本地缓存文件。
-| 文件名 | 大小 | 操作 | -
|---|
管理 API 密钥及系统参数设置。
-管理 Grok2API 的 Token 服务号池。
-| - | Token | -类型 | -状态 | -额度 | -备注 | -操作 | -
|---|
-Ww17`t|c!b9#DWE$DyK(Q~#b^i4Znvt|u^
zJYWF(T6%Yp7ml>#A?Ovs-hKO^XV0E+;=~ED{(_c2&8c9(`m0y3_ 通过 chat 接口与 Grok 进行会话聊天 通过 WebSocket 持续生成图片,实时展示 base64 瀑布流。 生成短视频,支持参考图与多种预设风格。 LiveKit 语音会话,连接 Grok Voice。 ${renderInline(joined)}
y9Y{^FS0US1krj#qKnb!|Rm<}1ZYjv{guFY&mY%go~_
zmvfuX>GCZr*KteNi+)1R<-+aY<<03q+K7~c^O@S!Hdz;?Kc0QZ$hj+9Y4cKo4Chat 聊天
- Imagine 瀑布流
-
-
Video 视频生成
- LiveKit 陪聊
- Chat 聊天
-```
-
-### `data-i18n-placeholder` — sets `placeholder`
-
-```html
-
-```
-
-### `data-i18n-title` — sets `title` (tooltip)
-
-```html
-
-```
-
-### `data-i18n-html` — sets `innerHTML` (available, not currently used)
-
-```html
-
-```
-
-> Use only when the translation contains HTML markup. Prefer `data-i18n` for plain text to avoid XSS risks.
-
-> Keep the Chinese fallback as the element's default content/attribute so the page renders correctly before translations load.
-
-## Translating a dynamic JS string
-
-Use the global `t(key, params?)` function:
-
-```js
-showToast(t('cache.clearSuccess', { size: data.result.size_mb }), 'success');
-```
-
-The `params` object replaces `{var}` placeholders in the locale string:
-
-```json
-{ "clearSuccess": "Cleared successfully, freed {size} MB" }
-```
-
-### Guard pattern for shared modules
-
-Shared code (e.g., `toast.js`, `admin-auth.js`) may run before `i18n.js` loads. Guard with `typeof t`:
-
-```js
-const label = typeof t === 'function' ? t('common.notice') : '提示';
-```
-
-## Translating dynamically injected HTML
-
-When HTML is injected at runtime (e.g., fetching a header fragment), call `I18n.applyToDOM(container)` after insertion:
-
-```js
-container.innerHTML = await res.text();
-
-if (window.I18n) {
- I18n.applyToDOM(container);
-}
-```
-
-This scans the container for `data-i18n-*` attributes and applies translations. The language toggle button text is set separately since it isn't a translation key:
-
-```js
-var toggle = container.querySelector('#lang-toggle');
-if (toggle) toggle.textContent = I18n.getLang() === 'zh' ? 'EN' : '中';
-```
-
-## API reference
-
-| Method | Description |
-|--------|-------------|
-| `t(key, params?)` | Translate a key. Returns the key itself if not found. |
-| `I18n.applyToDOM(root?)` | Scan `root` (default: `document`) for `data-i18n-*` attrs and apply translations. |
-| `I18n.setLang(lang)` | Set language, persist to localStorage, reload page. |
-| `I18n.toggleLang()` | Toggle between `zh` and `en`, reload. |
-| `I18n.getLang()` | Return current language code (`'zh'` or `'en'`). |
-| `I18n.onReady(cb)` | Run `cb` after translations have loaded. Runs immediately if already loaded. |
-
-## How to add a new language
-
-1. Create `public/static/i18n/locales/{code}.json` — copy `en.json` as a template
-2. Translate every key (545+ keys across 10 namespaces)
-3. In `i18n.js`, add the code to the `SUPPORTED` array:
- ```js
- var SUPPORTED = ['zh', 'en', 'ja'];
- ```
-4. Update the `toggleLang` function if you want rotation instead of binary toggle
-5. Update `#lang-toggle` button logic in `header.js` / `public-header.js`
-
-## How to add a new page
-
-Checklist:
-
-- [ ] Add a new namespace in both `zh.json` and `en.json` (e.g., `"mypage": { ... }`)
-- [ ] In the HTML: add `` before your page JS
-- [ ] In the HTML: add `data-i18n` / `data-i18n-placeholder` / `data-i18n-title` attributes to all user-visible elements
-- [ ] In the JS: use `t('mypage.keyName')` for any strings built in code
-- [ ] If injecting HTML dynamically: call `I18n.applyToDOM(container)` after insertion
-- [ ] If the page loads before `i18n.js`: use the `typeof t === 'function'` guard
-
-## Common patterns
-
-### Button with icon + translated text
-
-```html
-
-```
-
-Wrap the text in a `` so the icon is preserved.
-
-### Select options translated in JS
-
-```js
-const option = document.createElement('option');
-option.value = 'value';
-option.textContent = t('voice.optionLabel');
-select.appendChild(option);
-```
-
-### Interpolation for dynamic values
-
-```js
-// Locale: "lastClear": "Last cleared: {time}"
-setText(el, t('cache.lastClear', { time: timeText }));
-```
-
-### Table rows with inline translated strings
-
-```js
-body.innerHTML = ` `;
-```
-
-## Gotchas
-
-1. **Script order matters.** `i18n.js` must be loaded before page JS if the page JS calls `t()` at the top level. Otherwise use the `typeof t === 'function'` guard.
-
-2. **`t()` returns the key on miss.** If you see a raw key like `chat.title` in the UI, the key is missing from the locale JSON or was misspelled.
-
-3. **Keep both locale files in sync.** Every key in `zh.json` must exist in `en.json` and vice versa. Missing keys fall through to displaying the raw key string.
-
-4. **`innerHTML` vs `textContent`.** Use `data-i18n-html` only when the translation contains HTML markup. For plain text, always use `data-i18n` to avoid XSS risks.
-
-5. **Default content is Chinese.** The HTML files keep Chinese as inline fallback text. This means the page briefly shows Chinese before translations load — this is intentional and ensures the page is never blank.
-
-6. **`setLang()` reloads the page.** Language switching is not live — it persists to localStorage and triggers a full page reload.
-
-7. **`applyToDOM()` is idempotent.** Safe to call multiple times on the same container.
-
-8. **Shared modules need guards.** Files under `common/js/` (toast, header, admin-auth) may be loaded by pages that don't include `i18n.js`. Always guard `t()` calls in shared code.
diff --git a/app/assets/i18n/i18n.js b/app/assets/i18n/i18n.js
deleted file mode 100644
index 67141c95..00000000
--- a/app/assets/i18n/i18n.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * Grok2API i18n module — lightweight, zero-dependency internationalization.
- * Detects language from: localStorage > ?lang= URL param > browser > fallback (zh).
- * Translates static HTML via data-i18n / data-i18n-placeholder / data-i18n-title attrs.
- * Provides global t(key, params) for dynamic JS strings with {var} interpolation.
- */
-(function () {
- 'use strict';
-
- var STORAGE_KEY = 'grok2api_lang';
- var SUPPORTED = ['zh', 'en'];
- var DEFAULT = 'zh';
-
- var lang = DEFAULT;
- var data = {};
- var ready = false;
- var queue = [];
-
- function getStaticVersion() {
- var script = document.querySelector('script[src*="?v="]');
- if (!script || !script.src) return '';
- var m = script.src.match(/[?&]v=([^&]+)/);
- return m ? m[1] : '';
- }
-
- function detect() {
- try {
- var s = localStorage.getItem(STORAGE_KEY);
- if (s && SUPPORTED.indexOf(s) !== -1) return s;
- } catch (e) { /* ignore */ }
- try {
- var p = new URLSearchParams(location.search).get('lang');
- if (p && SUPPORTED.indexOf(p) !== -1) {
- try { localStorage.setItem(STORAGE_KEY, p); } catch (e) { /* ignore */ }
- return p;
- }
- } catch (e) { /* ignore */ }
- var b = (navigator.language || '').split('-')[0];
- if (SUPPORTED.indexOf(b) !== -1) return b;
- return DEFAULT;
- }
-
- function get(obj, key) {
- for (var parts = key.split('.'), i = 0; i < parts.length; i++) {
- if (obj == null) return undefined;
- obj = obj[parts[i]];
- }
- return obj;
- }
-
- function t(key, params) {
- var v = get(data, key);
- if (v === undefined) return key;
- if (params) {
- Object.keys(params).forEach(function (k) {
- v = v.replace(new RegExp('\\{' + k + '\\}', 'g'), params[k]);
- });
- }
- return v;
- }
-
- function applyToDOM(root) {
- var c = root || document;
- c.querySelectorAll('[data-i18n]').forEach(function (el) {
- var v = get(data, el.getAttribute('data-i18n'));
- if (v !== undefined) el.textContent = v;
- });
- c.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) {
- var v = get(data, el.getAttribute('data-i18n-placeholder'));
- if (v !== undefined) el.placeholder = v;
- });
- c.querySelectorAll('[data-i18n-title]').forEach(function (el) {
- var v = get(data, el.getAttribute('data-i18n-title'));
- if (v !== undefined) el.title = v;
- });
- c.querySelectorAll('[data-i18n-aria-label]').forEach(function (el) {
- var v = get(data, el.getAttribute('data-i18n-aria-label'));
- if (v !== undefined) el.setAttribute('aria-label', v);
- });
- c.querySelectorAll('[data-i18n-html]').forEach(function (el) {
- var v = get(data, el.getAttribute('data-i18n-html'));
- if (v !== undefined) el.innerHTML = v;
- });
- }
-
- function init() {
- lang = detect();
- document.documentElement.lang = lang === 'zh' ? 'zh-CN' : lang;
- var version = getStaticVersion();
- var url = '/static/i18n/locales/' + lang + '.json' + (version ? ('?v=' + encodeURIComponent(version)) : '');
- fetch(url)
- .then(function (r) { if (!r.ok) throw r; return r.json(); })
- .then(function (j) { data = j; })
- .catch(function () { data = {}; })
- .then(function () {
- ready = true;
- applyToDOM(document);
- queue.forEach(function (cb) { cb(); });
- queue = [];
- });
- }
-
- function setLang(l) {
- if (SUPPORTED.indexOf(l) === -1) return;
- try { localStorage.setItem(STORAGE_KEY, l); } catch (e) { /* ignore */ }
- location.reload();
- }
-
- window.I18n = {
- t: t,
- applyToDOM: applyToDOM,
- setLang: setLang,
- toggleLang: function () { setLang(lang === 'zh' ? 'en' : 'zh'); },
- getLang: function () { return lang; },
- onReady: function (cb) { if (ready) cb(); else queue.push(cb); }
- };
- window.t = t;
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
diff --git a/app/assets/i18n/locales/en.json b/app/assets/i18n/locales/en.json
deleted file mode 100644
index 999f699e..00000000
--- a/app/assets/i18n/locales/en.json
+++ /dev/null
@@ -1,589 +0,0 @@
-{
- "common": {
- "save": "Save",
- "cancel": "Cancel",
- "confirm": "Confirm",
- "delete": "Delete",
- "loading": "Loading...",
- "invalidKey": "Invalid key",
- "connectionFailed": "Connection failed",
- "requestFailed": "Request failed",
- "operationSuccess": "Operation successful",
- "gotIt": "Got it",
- "notice": "Notice",
- "rateLimitNotice": "The official GROK website update did not expose the rate-limits API, making it impossible to accurately calculate remaining Token usage. Please wait for the official API. Currently the count resets to 8 after auto-refresh.",
- "pleaseConfirm": "Please confirm",
- "ok": "OK",
- "close": "Close",
- "error": "Error",
- "unknownError": "Unknown error",
- "connectionInterrupted": "Connection interrupted",
- "taskInProgress": "A task is already in progress",
- "taskNoPause": "Current task does not support pausing",
- "batchNoPause": "Current batch task does not support pausing",
- "waitTaskFinish": "Please wait for the current task to finish",
- "pause": "Pause",
- "stop": "Stop",
- "selectAll": "Select all",
- "selected": "Selected",
- "items": "items",
- "export": "Export",
- "refresh": "Refresh",
- "load": "Load",
- "files": "files",
- "view": "View",
- "retry": "Retry",
- "copy": "Copy",
- "edit": "Edit",
- "loadFailed": "Load failed",
- "loadError": "Load failed: {msg}",
- "saveFailed": "Save failed",
- "saveError": "Save error: {msg}",
- "deleteFailed": "Delete failed",
- "deleteSuccess": "Deleted successfully",
- "notConnected": "Not connected",
- "connecting": "Connecting",
- "connected": "Connected",
- "connectionError": "Connection error",
- "generating": "Generating",
- "done": "Done",
- "failed": "Failed",
- "stopped": "Stopped",
- "terminated": "Terminated",
- "sending": "Sending",
- "fileReadFailed": "File read failed",
- "noFileSelected": "No file selected",
- "configurePublicKey": "Please configure Public Key first",
- "enterPrompt": "Please enter a prompt",
- "enterContent": "Please enter content",
- "alreadyRunning": "Already running",
- "createTaskFailed": "Failed to create task",
- "copyFailed": "Copy failed",
- "copied": "Copied",
- "generationFailed": "Generation failed",
- "partialError": "Partial error",
- "loadingInProgress": "Loading in progress, please wait",
- "cleaningInProgress": "Cleaning in progress, please wait",
- "noTokenSelected": "No Token selected",
- "clearCache": "Clear cache",
- "failureDetails": "Failure Details",
- "retryFailed": "Retry failed items"
- },
- "nav": {
- "tokenManage": "Token Mgmt",
- "configManage": "Config Mgmt",
- "cacheManage": "Cache Mgmt",
- "chat": "Chat",
- "imagine": "Imagine Gallery",
- "video": "Video Generation",
- "voice": "LiveKit Voice",
- "feedback": "Feedback",
- "logout": "Logout",
- "adminPanel": "Admin Panel",
- "storageMode": "Storage Mode"
- },
- "login": {
- "adminPageTitle": "Grok2API - Login",
- "adminTitle": "Admin Panel",
- "adminSubtitle": "Enter admin password to continue",
- "adminPlaceholder": "Admin Password (app_key)",
- "continue": "Continue",
- "publicPageTitle": "Grok2API - Public",
- "publicTitle": "Public Access",
- "publicSubtitle": "Enter Public Key (leave empty if not configured)",
- "publicPlaceholder": "Public Key",
- "enter": "Enter",
- "goToAdmin": "Go to Admin Panel"
- },
- "config": {
- "pageTitle": "Grok2API - Config",
- "title": "Configuration",
- "subtitle": "Manage API keys and system parameters.",
- "saving": "Saving...",
- "saved": "Saved",
- "configSaved": "Configuration saved",
- "invalidJson": "Invalid JSON: {field}",
- "appKeyRequired": "app_key cannot be empty (admin password)",
- "flaresolverrRequired": "FlareSolverr URL is required when auto-refresh is enabled",
- "generate": "Generate",
- "publicAccess": "Public Access",
- "noDesc": "No description available. Please refer to the documentation.",
- "sectionFallback": "{section} Settings",
- "sections": {
- "app": "App Settings",
- "proxy": "Proxy Config",
- "retry": "Retry Strategy",
- "chat": "Chat Config",
- "video": "Video Config",
- "image": "Image Config",
- "imagine_fast": "Imagine Fast Config",
- "asset": "Asset Config",
- "voice": "Voice Config",
- "token": "Token Pool Mgmt",
- "cache": "Cache Mgmt",
- "nsfw": "NSFW Config",
- "usage": "Usage Config"
- },
- "sectionDescs": {
- "proxy": "Incorrect configuration will cause 403 errors. The IP of the first request to Grok must match the IP used to obtain the CF Clearance. Subsequent IP changes will not cause 403."
- },
- "fields": {
- "app": {
- "api_key": {"title": "API Key", "desc": "Token for calling Grok2API services (optional, supports multiple, comma-separated or array)."},
- "app_key": {"title": "Admin Password", "desc": "Password for logging into the Grok2API admin panel (required)."},
- "function_enabled": {"title": "Enable Function Access", "desc": "Whether to enable the function access entry (disabled means function pages are inaccessible)."},
- "function_key": {"title": "Function Password", "desc": "Access password for function pages (optional)."},
- "app_url": {"title": "App URL", "desc": "External access URL for the Grok2API service, used for file link access."},
- "image_format": {"title": "Image Format", "desc": "Default image format (url or base64)."},
- "video_format": {"title": "Video Format", "desc": "Default video format (html or url, url is the processed link)."},
- "temporary": {"title": "Temporary Chat", "desc": "Whether to enable temporary chat mode by default."},
- "disable_memory": {"title": "Disable Memory", "desc": "Whether to disable Grok memory feature by default."},
- "stream": {"title": "Streaming", "desc": "Whether to enable streaming output by default."},
- "thinking": {"title": "Chain of Thought", "desc": "Whether to enable chain of thought output by default."},
- "dynamic_statsig": {"title": "Dynamic Fingerprint", "desc": "Whether to enable dynamic Statsig fingerprint generation by default."},
- "custom_instruction": {"title": "Custom Instruction", "desc": "Multi-line text passed through as Grok request parameter customPersonality."},
- "filter_tags": {"title": "Filter Tags", "desc": "Configure automatic filtering of special tags in Grok responses."}
- },
- "proxy": {
- "base_proxy_url": {"title": "Base Proxy URL", "desc": "Base service address for proxying requests to Grok website."},
- "asset_proxy_url": {"title": "Asset Proxy URL", "desc": "Address for proxying static resource (image/video) requests to Grok website."},
- "skip_proxy_ssl_verify": {"title": "Skip Proxy SSL Verify", "desc": "Enable when your proxy uses a self-signed certificate (only bypasses proxy certificate validation)."},
- "enabled": {"title": "Enable CF Auto-Refresh", "desc": "When enabled, automatically obtains cf_clearance through FlareSolverr."},
- "flaresolverr_url": {"title": "FlareSolverr URL", "desc": "HTTP address of FlareSolverr service (e.g. http://flaresolverr:8191)."},
- "refresh_interval": {"title": "Refresh Interval (sec)", "desc": "Time interval for auto-refreshing cf_clearance, recommended minimum 300 seconds."},
- "timeout": {"title": "Challenge Timeout (sec)", "desc": "Maximum time to wait for FlareSolverr to solve CF challenge."},
- "cf_clearance": {"title": "CF Clearance", "desc": "Cloudflare Clearance Cookie for bypassing anti-bot verification. Automatically managed when auto-refresh is enabled."},
- "browser": {"title": "Browser Fingerprint", "desc": "curl_cffi browser fingerprint identifier (e.g. chrome136). Automatically managed when auto-refresh is enabled."},
- "user_agent": {"title": "User-Agent", "desc": "HTTP request User-Agent string. Automatically managed when auto-refresh is enabled."}
- },
- "retry": {
- "max_retry": {"title": "Max Retries", "desc": "Maximum number of retries when Grok service request fails."},
- "retry_status_codes": {"title": "Retry Status Codes", "desc": "HTTP status codes that trigger a retry."},
- "reset_session_status_codes": {"title": "Session Reset Status Codes", "desc": "HTTP status codes that trigger session rebuild (used for proxy rotation)."},
- "retry_backoff_base": {"title": "Backoff Base", "desc": "Base delay (seconds) for retry backoff."},
- "retry_backoff_factor": {"title": "Backoff Factor", "desc": "Exponential multiplier for retry backoff."},
- "retry_backoff_max": {"title": "Backoff Max", "desc": "Maximum delay (seconds) for a single retry wait."},
- "retry_budget": {"title": "Backoff Budget", "desc": "Maximum total retry time (seconds) for a single request."}
- },
- "chat": {
- "concurrent": {"title": "Concurrency Limit", "desc": "Reverse API concurrency limit."},
- "timeout": {"title": "Request Timeout", "desc": "Reverse API timeout (seconds)."},
- "stream_timeout": {"title": "Stream Idle Timeout", "desc": "Streaming idle timeout (seconds)."}
- },
- "video": {
- "enable_public_asset": {"title": "Public Asset Link", "desc": "Whether to create a public asset link after video generation finishes."},
- "concurrent": {"title": "Concurrency Limit", "desc": "Reverse API concurrency limit."},
- "timeout": {"title": "Request Timeout", "desc": "Reverse API timeout (seconds)."},
- "stream_timeout": {"title": "Stream Idle Timeout", "desc": "Streaming idle timeout (seconds)."},
- "upscale_timing": {"title": "Upscale Timing", "desc": "Basic pool 720p upscale mode: single upscales after each extension round, complete upscales once after all rounds."}
- },
- "image": {
- "timeout": {"title": "Request Timeout", "desc": "WebSocket request timeout (seconds)."},
- "stream_timeout": {"title": "Stream Idle Timeout", "desc": "WebSocket streaming idle timeout (seconds)."},
- "final_timeout": {"title": "Final Image Timeout", "desc": "Timeout (seconds) to wait for final image after receiving medium image."},
- "blocked_grace_seconds": {"title": "Review Grace Seconds", "desc": "Grace seconds for suspected review/censorship after receiving medium image (default 10, configurable)."},
- "nsfw": {"title": "NSFW Mode", "desc": "Whether to enable NSFW for WebSocket requests."},
- "medium_min_bytes": {"title": "Medium Min Bytes", "desc": "Minimum byte size for medium quality image detection."},
- "final_min_bytes": {"title": "Final Min Bytes", "desc": "Minimum byte size for final image detection (typically JPG > 100KB)."},
- "blocked_parallel_enabled": {"title": "Enable Parallel Compensation", "desc": "Whether to enable parallel compensation when suspected review/blocking occurs."},
- "blocked_parallel_attempts": {"title": "Block Compensation Concurrency", "desc": "Number of parallel compensation attempts when suspected review/blocking prevents final image."}
- },
- "imagine_fast": {
- "n": {"title": "Generation Count", "desc": "Server-side unified generation count for grok-imagine-1.0-fast only (1-10)."},
- "size": {"title": "Image Size", "desc": "Server-side unified size for grok-imagine-1.0-fast only."},
- "response_format": {"title": "Response Format", "desc": "Server-side unified response format for grok-imagine-1.0-fast only."}
- },
- "asset": {
- "upload_concurrent": {"title": "Upload Concurrency", "desc": "Maximum concurrent uploads. Recommended: 30."},
- "upload_timeout": {"title": "Upload Timeout", "desc": "Upload timeout (seconds). Recommended: 60."},
- "download_concurrent": {"title": "Download Concurrency", "desc": "Maximum concurrent downloads. Recommended: 30."},
- "download_timeout": {"title": "Download Timeout", "desc": "Download timeout (seconds). Recommended: 60."},
- "list_concurrent": {"title": "Query Concurrency", "desc": "Maximum concurrent asset queries. Recommended: 10."},
- "list_timeout": {"title": "Query Timeout", "desc": "Asset query timeout (seconds). Recommended: 60."},
- "list_batch_size": {"title": "Query Batch Size", "desc": "Number of tokens per query batch. Recommended: 10."},
- "delete_concurrent": {"title": "Delete Concurrency", "desc": "Maximum concurrent asset deletions. Recommended: 10."},
- "delete_timeout": {"title": "Delete Timeout", "desc": "Asset deletion timeout (seconds). Recommended: 60."},
- "delete_batch_size": {"title": "Delete Batch Size", "desc": "Number of tokens per delete batch. Recommended: 10."}
- },
- "voice": {
- "timeout": {"title": "Request Timeout", "desc": "Voice request timeout (seconds)."}
- },
- "token": {
- "auto_refresh": {"title": "Auto Refresh", "desc": "Whether to enable automatic Token refresh."},
- "refresh_interval_hours": {"title": "Refresh Interval", "desc": "Time interval (hours) for regular Token refresh."},
- "super_refresh_interval_hours": {"title": "Super Refresh Interval", "desc": "Time interval (hours) for Super Token refresh."},
- "fail_threshold": {"title": "Failure Threshold", "desc": "Number of consecutive failures before a Token is marked unavailable."},
- "save_delay_ms": {"title": "Save Delay", "desc": "Delay (ms) for batching Token change writes."},
- "usage_flush_interval_sec": {"title": "Usage Flush Interval", "desc": "Minimum interval (seconds) for writing usage data to database."},
- "reload_interval_sec": {"title": "Sync Interval", "desc": "Token state refresh interval (seconds) in multi-worker scenarios."}
- },
- "cache": {
- "enable_auto_clean": {"title": "Auto Clean", "desc": "Whether to enable automatic cache cleanup based on size limit."},
- "limit_mb": {"title": "Clean Threshold", "desc": "Cache size threshold (MB) that triggers cleanup."}
- },
- "nsfw": {
- "concurrent": {"title": "Concurrency Limit", "desc": "Maximum concurrent requests for batch NSFW enable. Recommended: 10."},
- "batch_size": {"title": "Batch Size", "desc": "Batch processing count for NSFW enable. Recommended: 50."},
- "timeout": {"title": "Request Timeout", "desc": "Timeout for NSFW-related requests (seconds). Recommended: 60."}
- },
- "usage": {
- "concurrent": {"title": "Concurrency Limit", "desc": "Maximum concurrent requests for batch usage refresh. Recommended: 10."},
- "batch_size": {"title": "Batch Size", "desc": "Batch processing count for usage refresh. Recommended: 50."},
- "timeout": {"title": "Request Timeout", "desc": "Usage query timeout (seconds). Recommended: 60."}
- }
- }
- },
- "token": {
- "pageTitle": "Grok2API - Token Mgmt",
- "title": "Token List",
- "subtitle": "Manage the Grok2API Token service pool.",
- "import": "Import",
- "add": "Add",
- "statTotal": "Total Tokens",
- "statActive": "Active",
- "statCooling": "Rate Limited",
- "statInvalid": "Invalid",
- "statChatQuota": "Chat Remaining",
- "statImageQuota": "Image Remaining",
- "statChatConsumed": "Chat Consumed",
- "statImageConsumed": "Image Consumed",
- "statVideoQuota": "Video Remaining",
- "statVideoUnavailable": "N/A",
- "statTotalCalls": "Total Calls",
- "tabAll": "All",
- "tabActive": "Active",
- "tabCooling": "Rate Limited",
- "tabExpired": "Expired",
- "tabNsfw": "NSFW On",
- "tabNoNsfw": "NSFW Off",
- "statusFilterAria": "Token status filter",
- "tableToken": "Token",
- "tableType": "Type",
- "tableStatus": "Status",
- "tableQuota": "Quota",
- "tableQuotaConsumed": "Consumed",
- "tableNote": "Note",
- "tableActions": "Actions",
- "refreshStatus": "Refresh status",
- "emptyState": "No Tokens yet. Click Import or Add above.",
- "emptyFilterState": "No results for current filter. Try a different filter.",
- "selectPage": "Select page",
- "selectAllFiltered": "Select all",
- "clearSelection": "Clear selection",
- "prevPage": "Prev",
- "nextPage": "Next",
- "perPage": "{size} / page",
- "pagination": "Page {current} / {total} \u00b7 {count} items",
- "batchExport": "Export",
- "batchRefresh": "Refresh",
- "batchDisable": "Disable",
- "batchEnable": "Enable",
- "batchDelete": "Delete",
- "importTitle": "Batch Import Tokens",
- "importTargetPool": "Target Pool",
- "importTokenList": "Token List (one per line)",
- "importPlaceholder": "Paste Tokens, one per line...",
- "startImport": "Start Import",
- "editTitle": "Edit Token",
- "addTitle": "Add Token",
- "editType": "Type",
- "editQuota": "Quota",
- "editNote": "Note",
- "editNotePlaceholder": "Optional note",
- "tokenEmpty": "Token cannot be empty",
- "tokenExists": "Token already exists",
- "confirmDelete": "Are you sure you want to delete this Token?",
- "confirmDisable": "Are you sure you want to disable this Token?\n{token}",
- "confirmEnable": "Are you sure you want to enable this Token?\n{token}",
- "confirmBatchDelete": "Are you sure you want to delete {count} selected Tokens?",
- "confirmBatchDisable": "Are you sure you want to disable {count} selected Tokens?",
- "confirmBatchEnable": "Are you sure you want to enable {count} selected Tokens?",
- "disableToken": "Disable",
- "enableToken": "Enable",
- "disableDone": "Token disabled",
- "enableDone": "Token enabled",
- "batchDisableDone": "Batch disable complete",
- "batchEnableDone": "Batch enable complete",
- "noTokenToDisable": "All selected Tokens are already disabled",
- "noTokenToEnable": "All selected Tokens are already enabled",
- "deleteDone": "Delete complete",
- "refreshDone": "Refresh complete",
- "refreshSuccess": "Refresh successful",
- "refreshFailed": "Refresh failed",
- "refreshError": "Refresh failed: {msg}",
- "requestError": "Request error",
- "notValidJson": "Response is not valid JSON (HTTP {status})",
- "listEmpty": "List is empty",
- "stopRefresh": "Refresh stopped",
- "stopDelete": "Delete stopped",
- "stopNsfw": "NSFW stopped",
- "nsfwConfirm": "Enable NSFW mode for {count} selected Tokens?",
- "nsfwEnable": "Enable NSFW",
- "nsfwDone": "NSFW enable complete",
- "nsfwResult": "NSFW enable complete: {ok} succeeded, {fail} failed",
- "nsfwFailed": "Enable failed: {msg}",
- "emptyResponse": "Empty response (HTTP {status})"
- },
- "cache": {
- "pageTitle": "Grok2API - Cache Mgmt",
- "title": "Cache Management",
- "subtitle": "Manage local resources and online asset cache.",
- "localImages": "Local Images",
- "localVideos": "Local Videos",
- "onlineAssets": "Online Assets",
- "tableFile": "File",
- "tableSize": "Size",
- "tableTime": "Time",
- "tableActions": "Actions",
- "tableToken": "Token",
- "tableType": "Type",
- "tableAssetCount": "Asset Count",
- "tableLastClear": "Last Cleared",
- "selectPage": "Select page",
- "selectAllFiles": "Select all",
- "clearSelection": "Clear selection",
- "prevPage": "Prev",
- "nextPage": "Next",
- "perPageLabel": "Per page",
- "perPage": "{size} / page",
- "pagination": "Page {current} / {total} · {count} items",
- "notLoaded": "Not loaded",
- "noAccounts": "No accounts available",
- "noFiles": "No files",
- "noTokenAvailable": "No Token available",
- "cannotConnect": "Cannot connect",
- "lastClear": "Last cleared: {time}",
- "clear": "Clear",
- "clean": "Clean",
- "confirmClearImage": "Clear all local image cache?",
- "confirmClearVideo": "Clear all local video cache?",
- "clearSuccess": "Cleanup successful, freed {size} MB",
- "clearFailed": "Cleanup failed",
- "confirmDeleteFile": "Are you sure you want to delete this file?",
- "confirmBatchDeleteFiles": "Are you sure you want to delete {count} selected files?",
- "noFilesSelected": "No files selected",
- "deletedFiles": "Deleted {count} files",
- "deleteResult": "Delete complete: {success} succeeded, {failed} failed",
- "loadStatsFailed": "Failed to load statistics",
- "selectAccountsToLoad": "Please select accounts to load",
- "selectAccountsToClear": "Please select accounts to clear",
- "confirmClearAccounts": "Clear online assets for {count} selected accounts?",
- "confirmClearAccount": "Clear online assets for account {label}?",
- "batchCleanInProgress": "Batch cleaning online assets, please wait...",
- "cleanInProgress": "Cleaning online assets, please wait...",
- "batchCleanDone": "Batch cleanup complete",
- "cleanResult": "Cleanup complete (succeeded: {success}, failed: {failed})",
- "cleanFailedEntry": "Cleanup failed",
- "requestTimeout": "Request timed out or failed",
- "loadDone": "Load complete",
- "loadingStatus": "Loading",
- "loadStopped": "Load stopped",
- "loadFailedMsg": "Load failed: {msg}",
- "stoppedLoadRequests": "Remaining load requests stopped",
- "cleanStopped": "Clean stopped",
- "cleanFailedMsg": "Clean failed: {msg}",
- "stoppedCleanRequests": "Remaining clean requests stopped"
- },
- "chat": {
- "pageTitle": "Grok2API - Chat",
- "title": "Chat",
- "subtitle": "Chat with Grok via the chat API",
- "sessions": "Sessions",
- "newChat": "New",
- "collapseSidebar": "Collapse",
- "expandSidebar": "Expand",
- "sessionList": "Session list",
- "newSession": "New Session",
- "ready": "Ready",
- "emptyState": "Type a message to start a conversation.",
- "uploadFile": "Upload file",
- "placeholder": "Ask anything",
- "settings": "Settings",
- "send": "Send",
- "temperature": "Temperature",
- "topP": "Top P",
- "systemPrompt": "System Prompt",
- "systemPromptPlaceholder": "Optional, set system prompt",
- "fileLabel": "[File]",
- "compositeContent": "[Composite]",
- "storageFull": "Local storage is full, some sessions were not saved",
- "attachmentNoEdit": "Attachment messages cannot be edited yet",
- "saveEdit": "Save",
- "saveEditTitle": "Save edit",
- "cancelEdit": "Cancel",
- "cancelEditTitle": "Cancel edit",
- "contentEmpty": "Content cannot be empty",
- "editMessage": "Edit",
- "editMessageTitle": "Edit message content",
- "regenerate": "Regenerate",
- "regenerateTitle": "Regenerate response from here",
- "retryTitle": "Retry last response",
- "editAnswer": "Edit",
- "editAnswerTitle": "Edit response content",
- "copyAnswer": "Copy",
- "copyAnswerTitle": "Copy response content",
- "feedback": "Feedback",
- "feedbackTitle": "Feedback to Grok2API",
- "noContentToCopy": "No content to copy",
- "noChatToRetry": "No conversation to retry",
- "requestFailedCheck": "Request failed, please check service status",
- "requestFailedStatus": "Request failed: {status}",
- "clickRetry": "Click to retry",
- "thinking": "Thinking",
- "thinkingSec": "Thinking {sec}s",
- "thought": "Thought",
- "thinkLabel": "Thinking",
- "empty": "(empty)",
- "toolWebSearch": "Web search",
- "toolImageSearch": "Image search",
- "toolAgentThink": "Reasoning",
- "toolDefault": "Tool"
- },
- "imagine": {
- "pageTitle": "Grok2API - Imagine Gallery",
- "title": "Imagine Gallery",
- "subtitle": "Continuously generate images via WebSocket, real-time base64 gallery.",
- "genSettings": "Generation Settings",
- "prompt": "Prompt",
- "promptPlaceholder": "Describe the image you want, e.g.: futuristic city neon rain at night, wide angle photography",
- "autoFollow": "Auto Follow",
- "autoFollowDesc": "Scroll to latest",
- "autoSave": "Auto Save",
- "autoSaveDesc": "Auto-save images",
- "aspectRatio": "Aspect Ratio",
- "ratio2_3": "2:3 Portrait",
- "ratio1_1": "1:1 Square",
- "ratio3_2": "3:2 Landscape",
- "ratio16_9": "16:9 Wide",
- "ratio9_16": "9:16 Tall",
- "concurrent": "Concurrency",
- "tasks": "{n} tasks",
- "concurrentTask1": "1 task",
- "concurrentTask2": "2 tasks",
- "concurrentTask3": "3 tasks",
- "autoFilter": "Auto Filter",
- "autoFilterDesc": "Filter substandard images",
- "nsfwLabel": "NSFW",
- "nsfwOn": "On",
- "nsfwOff": "Off",
- "saveLocation": "Save Location",
- "browserDefault": "Browser default location",
- "reverseOrder": "Reverse Order",
- "reverseOrderDesc": "Show newest on top",
- "connectionStatus": "Connection Status",
- "connectionMode": "Connection Mode",
- "connectionModeAria": "Connection mode",
- "imageCount": "Image Count",
- "activeTasks": "Active Tasks",
- "avgTime": "Avg Time",
- "gallery": "Gallery",
- "waitingTitle": "Waiting for connection",
- "waitingSubtitle": "Generated images will appear here after starting a task",
- "start": "Start",
- "batch": "Batch",
- "batchDownloadTitle": "Batch download",
- "selectAll": "Select all",
- "deselectAll": "Deselect all",
- "download": "Download",
- "startedTasks": "Started {count} concurrent tasks",
- "startedTasksSSE": "Started {count} concurrent tasks (SSE)",
- "generatingSSE": "Generating (SSE)",
- "selectFolder": "Selected folder: {name}",
- "selectFolderFailed": "Failed to select folder",
- "noImagesSelected": "Please select images to download first",
- "jszipFailed": "JSZip library failed to load, please refresh and try again",
- "packing": "Packing {count} images...",
- "packingBtn": "Packing...",
- "packingProgress": "Packing... ({done}/{total})",
- "noImagesDownloaded": "No images were downloaded successfully",
- "generatingZip": "Generating ZIP...",
- "packSuccess": "Successfully packed {count} images",
- "packFailed": "Packing failed, please try again"
- },
- "video": {
- "pageTitle": "Grok2API - Video Generation",
- "title": "Video Generation",
- "subtitle": "Generate short videos with up to 7 reference images, @图N placeholders, and preset styles.",
- "startGenerate": "Generate",
- "genSettings": "Generation Settings",
- "prompt": "Prompt",
- "promptPlaceholder": "e.g.: @图1 neon rainy street at night, @图2 subject looking back and smiling, slow motion, film grain",
- "promptTip": "Use @图1 to @图7 in the prompt to reference images by upload order.",
- "referenceImage": "Reference Image",
- "referenceImagePlaceholder": "One https://... or data:image/... per line, up to 7 images",
- "aspectRatio": "Aspect Ratio",
- "ratio3_2": "3:2 Landscape",
- "ratio2_3": "2:3 Portrait",
- "ratio16_9": "16:9 Wide",
- "ratio9_16": "9:16 Tall",
- "ratio1_1": "1:1 Square",
- "duration": "Duration",
- "seconds": "{n}s",
- "resolution": "Resolution",
- "stylePreset": "Style Preset",
- "upload": "Upload",
- "clearImage": "Clear",
- "runStatus": "Run Status",
- "elapsedTime": "Elapsed {sec}s",
- "elapsedTimeNone": "Elapsed -",
- "metaRatio": "Ratio",
- "metaDuration": "Duration",
- "metaResolution": "Resolution",
- "metaPreset": "Preset",
- "videoPreview": "Video Preview",
- "clearPreview": "Clear",
- "waitingGenerate": "Waiting for video generation",
- "videoTitle": "Video {n}",
- "open": "Open",
- "generatingPlaceholder": "Generating...",
- "superResolution": "Super Resolution",
- "superResolutionInProgress": "Super resolution in progress",
- "alreadyGenerating": "Already generating",
- "referenceConflict": "Reference images: choose either URL/Base64 list or file upload",
- "referenceLimit": "A maximum of 7 reference images is supported",
- "noReferenceSelected": "No reference images selected",
- "downloadFailed": "Download failed, please check if the video link is accessible",
- "sec6": "6s",
- "sec10": "10s",
- "sec15": "15s"
- },
- "voice": {
- "pageTitle": "Grok2API - LiveKit Voice",
- "title": "LiveKit Voice",
- "subtitle": "LiveKit voice session, connect to Grok Voice.",
- "startSession": "Start Session",
- "stopSession": "Stop Session",
- "connectionSettings": "Connection Settings",
- "voiceLabel": "Voice",
- "personalityLabel": "Personality",
- "speedLabel": "Speed",
- "settingsHint": "Tip: Voice / Personality settings are sent to the server before connecting.",
- "sessionLog": "Session Log",
- "clearLog": "Clear",
- "copyLog": "Copy",
- "sessionStatus": "Session Status",
- "audioOutput": "Audio Output",
- "audioHint": "Subscribed audio tracks will be automatically inserted here.",
- "livekitSDKError": "Error: LiveKit SDK failed to load properly, please refresh the page",
- "livekitLoadFailed": "LiveKit SDK failed to load",
- "secureContextBrowser": "Please use a modern browser and allow microphone access",
- "secureContextHTTPS": "Please use HTTPS or access from localhost",
- "secureContextError": "Current environment does not support microphone access, {hint}",
- "connectingStatus": "Connecting",
- "fetchingToken": "Fetching Token...",
- "fetchTokenFailed": "Failed to get Token: {status}",
- "fetchTokenSuccess": "Token obtained successfully",
- "participantConnected": "Participant connected: {identity}",
- "participantDisconnected": "Participant disconnected: {identity}",
- "trackSubscribed": "Track subscribed: {kind}",
- "disconnected": "Disconnected",
- "connectedToServer": "Connected to LiveKit server",
- "inCall": "In call",
- "openingMic": "Opening microphone...",
- "voiceEnabled": "Voice enabled",
- "voiceConnected": "Voice connected successfully",
- "errorPrefix": "Error: {msg}",
- "logCopied": "Log copied",
- "copyLogFailed": "Copy failed, please select manually"
- }
-}
diff --git a/app/assets/i18n/locales/zh.json b/app/assets/i18n/locales/zh.json
deleted file mode 100644
index 329ed50b..00000000
--- a/app/assets/i18n/locales/zh.json
+++ /dev/null
@@ -1,589 +0,0 @@
-{
- "common": {
- "save": "保存",
- "cancel": "取消",
- "confirm": "确认",
- "delete": "删除",
- "loading": "加载中...",
- "invalidKey": "密钥无效",
- "connectionFailed": "连接失败",
- "requestFailed": "请求失败",
- "operationSuccess": "操作成功",
- "gotIt": "我知道了",
- "notice": "提示",
- "rateLimitNotice": "GROK 官方网页更新后未真实暴露 rate-limits 接口,导致无法准确计算 Token 剩余,请耐心等待官方接口上线,目前自动刷新后会更新为 8 次",
- "pleaseConfirm": "请确认",
- "ok": "确定",
- "close": "关闭",
- "error": "错误",
- "unknownError": "未知错误",
- "connectionInterrupted": "连接中断",
- "taskInProgress": "当前有任务进行中",
- "taskNoPause": "当前任务不支持暂停",
- "batchNoPause": "当前批量任务不支持暂停",
- "waitTaskFinish": "请等待当前任务结束",
- "pause": "暂停",
- "stop": "终止",
- "selectAll": "全选",
- "selected": "已选择",
- "items": "项",
- "export": "导出",
- "refresh": "刷新",
- "load": "加载",
- "files": "个文件",
- "view": "查看",
- "retry": "重试",
- "copy": "复制",
- "edit": "编辑",
- "loadFailed": "加载失败",
- "loadError": "加载失败: {msg}",
- "saveFailed": "保存失败",
- "saveError": "保存错误: {msg}",
- "deleteFailed": "删除失败",
- "deleteSuccess": "删除成功",
- "notConnected": "未连接",
- "connecting": "连接中",
- "connected": "连接正常",
- "connectionError": "连接错误",
- "generating": "生成中",
- "done": "完成",
- "failed": "失败",
- "stopped": "已停止",
- "terminated": "已终止",
- "sending": "发送中",
- "fileReadFailed": "文件读取失败",
- "noFileSelected": "未选择文件",
- "configurePublicKey": "请先配置 Public Key",
- "enterPrompt": "请输入提示词",
- "enterContent": "请输入内容",
- "alreadyRunning": "已在运行中",
- "createTaskFailed": "创建任务失败",
- "copyFailed": "复制失败",
- "copied": "已复制",
- "generationFailed": "生成失败",
- "partialError": "部分异常",
- "loadingInProgress": "正在加载中,请稍候",
- "cleaningInProgress": "正在清理中,请稍候",
- "noTokenSelected": "未选择 Token",
- "clearCache": "清空缓存",
- "failureDetails": "失败详情",
- "retryFailed": "重试失败项"
- },
- "nav": {
- "tokenManage": "Token管理",
- "configManage": "配置管理",
- "cacheManage": "缓存管理",
- "chat": "Chat 聊天",
- "imagine": "Imagine 瀑布流",
- "video": "Video 视频生成",
- "voice": "LiveKit 陪聊",
- "feedback": "反馈",
- "logout": "退出",
- "adminPanel": "管理后台",
- "storageMode": "存储模式"
- },
- "login": {
- "adminPageTitle": "Grok2API - 登录",
- "adminTitle": "管理后台",
- "adminSubtitle": "请输入后台密码以继续",
- "adminPlaceholder": "后台密码 (app_key)",
- "continue": "继续",
- "publicPageTitle": "Grok2API - Public",
- "publicTitle": "Public Access",
- "publicSubtitle": "请输入 Public Key(如未配置可直接进入)",
- "publicPlaceholder": "Public Key",
- "enter": "进入",
- "goToAdmin": "进入管理后台"
- },
- "config": {
- "pageTitle": "Grok2API - 配置管理",
- "title": "配置管理",
- "subtitle": "管理 API 密钥及系统参数设置。",
- "saving": "保存中...",
- "saved": "成功",
- "configSaved": "配置已保存",
- "invalidJson": "无效的 JSON: {field}",
- "appKeyRequired": "app_key 不能为空(后台密码)",
- "flaresolverrRequired": "启用自动刷新时必须填写 FlareSolverr 地址",
- "generate": "生成",
- "publicAccess": "功能玩法",
- "noDesc": "暂无说明,请参考配置文档。",
- "sectionFallback": "{section} 设置",
- "sections": {
- "app": "应用设置",
- "proxy": "代理配置",
- "retry": "重试策略",
- "chat": "对话配置",
- "video": "视频配置",
- "image": "图像配置",
- "imagine_fast": "Imagine Fast 配置",
- "asset": "资产配置",
- "voice": "语音配置",
- "token": "Token 池管理",
- "cache": "缓存管理",
- "nsfw": "NSFW 配置",
- "usage": "Usage 配置"
- },
- "sectionDescs": {
- "proxy": "配置不正确将导致 403 错误。服务首次请求 Grok 时的 IP 必须与获取 CF Clearance 时的 IP 一致,后续服务器请求 IP 变化不会导致 403。"
- },
- "fields": {
- "app": {
- "api_key": {"title": "API 密钥", "desc": "调用 Grok2API 服务的 Token(可选,支持多个,逗号分隔或数组)。"},
- "app_key": {"title": "后台密码", "desc": "登录 Grok2API 管理后台的密码(必填)。"},
- "function_enabled": {"title": "启用功能玩法", "desc": "是否启用功能玩法入口(关闭则功能玩法页面不可访问)。"},
- "function_key": {"title": "Function 密码", "desc": "功能玩法页面的访问密码(可选)。"},
- "app_url": {"title": "应用地址", "desc": "当前 Grok2API 服务的外部访问 URL,用于文件链接访问。"},
- "image_format": {"title": "图片格式", "desc": "默认生成的图片格式(url 或 base64)。"},
- "video_format": {"title": "视频格式", "desc": "默认生成的视频格式(html 或 url,url 为处理后的链接)。"},
- "temporary": {"title": "临时对话", "desc": "是否默认启用临时对话模式。"},
- "disable_memory": {"title": "禁用记忆", "desc": "是否默认禁用 Grok 记忆功能。"},
- "stream": {"title": "流式响应", "desc": "是否默认启用流式输出。"},
- "thinking": {"title": "思维链", "desc": "是否默认启用思维链输出。"},
- "dynamic_statsig": {"title": "动态指纹", "desc": "是否默认启用动态生成 Statsig 指纹。"},
- "custom_instruction": {"title": "自定义指令", "desc": "多行文本,会透传为 Grok 请求参数 customPersonality。"},
- "filter_tags": {"title": "过滤标签", "desc": "设置自动过滤 Grok 响应中的特殊标签。"}
- },
- "proxy": {
- "base_proxy_url": {"title": "基础代理 URL", "desc": "代理请求到 Grok 官网的基础服务地址。"},
- "asset_proxy_url": {"title": "资源代理 URL", "desc": "代理请求到 Grok 官网的静态资源(图片/视频)地址。"},
- "skip_proxy_ssl_verify": {"title": "跳过代理 SSL 校验", "desc": "代理使用自签名证书时启用(仅放行代理证书校验)。"},
- "enabled": {"title": "启用 CF 自动刷新", "desc": "启用后将通过 FlareSolverr 自动获取 cf_clearance。"},
- "flaresolverr_url": {"title": "FlareSolverr 地址", "desc": "FlareSolverr 服务的 HTTP 地址(如 http://flaresolverr:8191)。"},
- "refresh_interval": {"title": "刷新间隔(秒)", "desc": "自动刷新 cf_clearance 的时间间隔,建议不低于 300 秒。"},
- "timeout": {"title": "挑战超时(秒)", "desc": "等待 FlareSolverr 解决 CF 挑战的最大时间。"},
- "cf_clearance": {"title": "CF Clearance", "desc": "Cloudflare Clearance Cookie,用于绕过反爬虫验证。启用自动刷新时由系统自动管理。"},
- "browser": {"title": "浏览器指纹", "desc": "curl_cffi 浏览器指纹标识(如 chrome136)。启用自动刷新时由系统自动管理。"},
- "user_agent": {"title": "User-Agent", "desc": "HTTP 请求的 User-Agent 字符串。启用自动刷新时由系统自动管理。"}
- },
- "retry": {
- "max_retry": {"title": "最大重试次数", "desc": "请求 Grok 服务失败时的最大重试次数。"},
- "retry_status_codes": {"title": "重试状态码", "desc": "触发重试的 HTTP 状态码列表。"},
- "reset_session_status_codes": {"title": "重建状态码", "desc": "触发重建 session 的 HTTP 状态码列表(用于轮换代理)。"},
- "retry_backoff_base": {"title": "退避基数", "desc": "重试退避的基础延迟(秒)。"},
- "retry_backoff_factor": {"title": "退避倍率", "desc": "重试退避的指数放大系数。"},
- "retry_backoff_max": {"title": "退避上限", "desc": "单次重试等待的最大延迟(秒)。"},
- "retry_budget": {"title": "退避预算", "desc": "单次请求的最大重试总耗时(秒)。"}
- },
- "chat": {
- "concurrent": {"title": "并发上限", "desc": "Reverse 接口并发上限。"},
- "timeout": {"title": "请求超时", "desc": "Reverse 接口超时时间(秒)。"},
- "stream_timeout": {"title": "流空闲超时", "desc": "流式空闲超时时间(秒)。"}
- },
- "video": {
- "enable_public_asset": {"title": "公开资产链接", "desc": "是否开启生成结束后创建 Public 资产。"},
- "concurrent": {"title": "并发上限", "desc": "Reverse 接口并发上限。"},
- "timeout": {"title": "请求超时", "desc": "Reverse 接口超时时间(秒)。"},
- "stream_timeout": {"title": "流空闲超时", "desc": "流式空闲超时时间(秒)。"},
- "upscale_timing": {"title": "超分时机", "desc": "Basic 号池 720p 超分模式:single 为每轮扩展后超分,complete 为全部扩展完成后再超分。"}
- },
- "image": {
- "timeout": {"title": "请求超时", "desc": "WebSocket 请求超时时间(秒)。"},
- "stream_timeout": {"title": "流空闲超时", "desc": "WebSocket 流式空闲超时时间(秒)。"},
- "final_timeout": {"title": "最终图超时", "desc": "收到中等图后等待最终图的超时秒数。"},
- "blocked_grace_seconds": {"title": "审查宽限秒数", "desc": "收到中等图后,判定疑似被审查的宽限秒数(默认 10 秒,可自定义)。"},
- "nsfw": {"title": "NSFW 模式", "desc": "WebSocket 请求是否启用 NSFW。"},
- "medium_min_bytes": {"title": "中等图最小字节", "desc": "判定中等质量图的最小字节数。"},
- "final_min_bytes": {"title": "最终图最小字节", "desc": "判定最终图的最小字节数(通常 JPG > 100KB)。"},
- "blocked_parallel_enabled": {"title": "启用并行补偿", "desc": "疑似审查/拦截时,是否启用并行补偿生成。"},
- "blocked_parallel_attempts": {"title": "拦截补偿并发次数", "desc": "疑似审查/拦截导致无最终图时,自动并行补偿生成次数。"}
- },
- "imagine_fast": {
- "n": {"title": "生成数量", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一生成数量(1-10)。"},
- "size": {"title": "图片尺寸", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一尺寸。"},
- "response_format": {"title": "响应格式", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一返回格式。"}
- },
- "asset": {
- "upload_concurrent": {"title": "上传并发", "desc": "上传接口的最大并发数。推荐 30。"},
- "upload_timeout": {"title": "上传超时", "desc": "上传接口超时时间(秒)。推荐 60。"},
- "download_concurrent": {"title": "下载并发", "desc": "下载接口的最大并发数。推荐 30。"},
- "download_timeout": {"title": "下载超时", "desc": "下载接口超时时间(秒)。推荐 60。"},
- "list_concurrent": {"title": "查询并发", "desc": "资产查询接口的最大并发数。推荐 10。"},
- "list_timeout": {"title": "查询超时", "desc": "资产查询接口超时时间(秒)。推荐 60。"},
- "list_batch_size": {"title": "查询批次大小", "desc": "单次查询可处理的 Token 数量。推荐 10。"},
- "delete_concurrent": {"title": "删除并发", "desc": "资产删除接口的最大并发数。推荐 10。"},
- "delete_timeout": {"title": "删除超时", "desc": "资产删除接口超时时间(秒)。推荐 60。"},
- "delete_batch_size": {"title": "删除批次大小", "desc": "单次删除可处理的 Token 数量。推荐 10。"}
- },
- "voice": {
- "timeout": {"title": "请求超时", "desc": "Voice 请求超时时间(秒)。"}
- },
- "token": {
- "auto_refresh": {"title": "自动刷新", "desc": "是否开启 Token 自动刷新机制。"},
- "refresh_interval_hours": {"title": "刷新间隔", "desc": "普通 Token 刷新的时间间隔(小时)。"},
- "super_refresh_interval_hours": {"title": "Super 刷新间隔", "desc": "Super Token 刷新的时间间隔(小时)。"},
- "fail_threshold": {"title": "失败阈值", "desc": "单个 Token 连续失败多少次后被标记为不可用。"},
- "save_delay_ms": {"title": "保存延迟", "desc": "Token 变更合并写入的延迟(毫秒)。"},
- "usage_flush_interval_sec": {"title": "用量落库间隔", "desc": "用量类字段写入数据库的最小间隔(秒)。"},
- "reload_interval_sec": {"title": "同步间隔", "desc": "多 worker 场景下 Token 状态刷新间隔(秒)。"}
- },
- "cache": {
- "enable_auto_clean": {"title": "自动清理", "desc": "是否启用缓存自动清理,开启后按上限自动回收。"},
- "limit_mb": {"title": "清理阈值", "desc": "缓存大小阈值(MB),超过阈值会触发清理。"}
- },
- "nsfw": {
- "concurrent": {"title": "并发上限", "desc": "批量开启 NSFW 模式时的并发请求上限。推荐 10。"},
- "batch_size": {"title": "批次大小", "desc": "批量开启 NSFW 模式的单批处理数量。推荐 50。"},
- "timeout": {"title": "请求超时", "desc": "NSFW 开启相关请求的超时时间(秒)。推荐 60。"}
- },
- "usage": {
- "concurrent": {"title": "并发上限", "desc": "批量刷新用量时的并发请求上限。推荐 10。"},
- "batch_size": {"title": "批次大小", "desc": "批量刷新用量的单批处理数量。推荐 50。"},
- "timeout": {"title": "请求超时", "desc": "用量查询接口的超时时间(秒)。推荐 60。"}
- }
- }
- },
- "token": {
- "pageTitle": "Grok2API - Token 管理",
- "title": "Token 列表",
- "subtitle": "管理 Grok2API 的 Token 服务号池。",
- "import": "导入",
- "add": "添加",
- "statTotal": "Token 总数",
- "statActive": "Token 正常",
- "statCooling": "Token 限流",
- "statInvalid": "Token 失效",
- "statChatQuota": "Chat 剩余",
- "statImageQuota": "Image 剩余",
- "statChatConsumed": "Chat 已消耗",
- "statImageConsumed": "Image 已消耗",
- "statVideoQuota": "Video 剩余",
- "statVideoUnavailable": "无法统计",
- "statTotalCalls": "总调用次数",
- "tabAll": "全部",
- "tabActive": "正常",
- "tabCooling": "限流",
- "tabExpired": "失效",
- "tabNsfw": "已开 NSFW",
- "tabNoNsfw": "未开 NSFW",
- "statusFilterAria": "Token 状态筛选",
- "tableToken": "Token",
- "tableType": "类型",
- "tableStatus": "状态",
- "tableQuota": "额度",
- "tableQuotaConsumed": "已消耗",
- "tableNote": "备注",
- "tableActions": "操作",
- "refreshStatus": "刷新状态",
- "emptyState": "暂无 Token,请点击右上角导入或添加。",
- "emptyFilterState": "当前筛选无结果,请切换筛选条件。",
- "selectPage": "全选本页",
- "selectAllFiltered": "全选全部",
- "clearSelection": "取消全选",
- "prevPage": "上一页",
- "nextPage": "下一页",
- "perPage": "{size} / 页",
- "pagination": "第 {current} / {total} 页 · 共 {count} 条",
- "batchExport": "导出",
- "batchRefresh": "刷新",
- "batchDisable": "禁用",
- "batchEnable": "启用",
- "batchDelete": "删除",
- "importTitle": "批量导入 Token",
- "importTargetPool": "目标 Pool",
- "importTokenList": "Token 列表 (每行一个)",
- "importPlaceholder": "粘贴 Token,一行一个...",
- "startImport": "开始导入",
- "editTitle": "编辑 Token",
- "addTitle": "添加 Token",
- "editType": "类型",
- "editQuota": "额度",
- "editNote": "备注",
- "editNotePlaceholder": "可选备注",
- "tokenEmpty": "Token 不能为空",
- "tokenExists": "Token 已存在",
- "confirmDelete": "确定要删除此 Token 吗?",
- "confirmDisable": "确定要禁用该 Token 吗?\n{token}",
- "confirmEnable": "确定要启用该 Token 吗?\n{token}",
- "confirmBatchDelete": "确定要删除选中的 {count} 个 Token 吗?",
- "confirmBatchDisable": "确定要禁用选中的 {count} 个 Token 吗?",
- "confirmBatchEnable": "确定要启用选中的 {count} 个 Token 吗?",
- "disableToken": "禁用",
- "enableToken": "启用",
- "disableDone": "Token 已禁用",
- "enableDone": "Token 已启用",
- "batchDisableDone": "批量禁用完成",
- "batchEnableDone": "批量启用完成",
- "noTokenToDisable": "选中的 Token 已全部是禁用状态",
- "noTokenToEnable": "选中的 Token 已全部是启用状态",
- "deleteDone": "删除完成",
- "refreshDone": "刷新完成",
- "refreshSuccess": "刷新成功",
- "refreshFailed": "刷新失败",
- "refreshError": "刷新失败: {msg}",
- "requestError": "请求错误",
- "notValidJson": "响应不是有效 JSON (HTTP {status})",
- "listEmpty": "列表为空",
- "stopRefresh": "已终止刷新",
- "stopDelete": "已终止删除",
- "stopNsfw": "已终止 NSFW",
- "nsfwConfirm": "是否为选中的 {count} 个 Token 开启 NSFW 模式?",
- "nsfwEnable": "开启 NSFW",
- "nsfwDone": "NSFW 开启完成",
- "nsfwResult": "NSFW 开启完成:成功 {ok},失败 {fail}",
- "nsfwFailed": "开启失败: {msg}",
- "emptyResponse": "空响应 (HTTP {status})"
- },
- "cache": {
- "pageTitle": "Grok2API - 缓存管理",
- "title": "缓存管理",
- "subtitle": "管理本地资源与在线资产缓存。",
- "localImages": "本地图片",
- "localVideos": "本地视频",
- "onlineAssets": "在线资产",
- "tableFile": "文件",
- "tableSize": "大小",
- "tableTime": "时间",
- "tableActions": "操作",
- "tableToken": "Token",
- "tableType": "类型",
- "tableAssetCount": "资产数",
- "tableLastClear": "上次清空时间",
- "selectPage": "全选本页",
- "selectAllFiles": "全选全部",
- "clearSelection": "取消全选",
- "prevPage": "上一页",
- "nextPage": "下一页",
- "perPageLabel": "每页",
- "perPage": "{size} / 页",
- "pagination": "第 {current} / {total} 页 · 共 {count} 条",
- "notLoaded": "未加载",
- "noAccounts": "暂无可用账号",
- "noFiles": "暂无文件",
- "noTokenAvailable": "无可用 Token",
- "cannotConnect": "无法连接",
- "lastClear": "上次清空:{time}",
- "clear": "清空",
- "clean": "清理",
- "confirmClearImage": "确定要清空本地图片缓存吗?",
- "confirmClearVideo": "确定要清空本地视频缓存吗?",
- "clearSuccess": "清理成功,释放 {size} MB",
- "clearFailed": "清理失败",
- "confirmDeleteFile": "确定要删除该文件吗?",
- "confirmBatchDeleteFiles": "确定要删除选中的 {count} 个文件吗?",
- "noFilesSelected": "未选择文件",
- "deletedFiles": "已删除 {count} 个文件",
- "deleteResult": "删除完成:成功 {success},失败 {failed}",
- "loadStatsFailed": "加载统计失败",
- "selectAccountsToLoad": "请选择要加载的账号",
- "selectAccountsToClear": "请选择要清空的账号",
- "confirmClearAccounts": "确定要清空选中的 {count} 个账号在线资产吗?",
- "confirmClearAccount": "确定要清空账号 {label} 的在线资产吗?",
- "batchCleanInProgress": "正在批量清理在线资产,请稍候...",
- "cleanInProgress": "正在清理在线资产,请稍候...",
- "batchCleanDone": "批量清理完成",
- "cleanResult": "清理完成 (成功: {success}, 失败: {failed})",
- "cleanFailedEntry": "清理失败",
- "requestTimeout": "请求超时或失败",
- "loadDone": "加载完成",
- "loadingStatus": "加载中",
- "loadStopped": "已终止加载",
- "loadFailedMsg": "加载失败: {msg}",
- "stoppedLoadRequests": "已终止剩余加载请求",
- "cleanStopped": "已终止清理",
- "cleanFailedMsg": "清理失败: {msg}",
- "stoppedCleanRequests": "已终止剩余清理请求"
- },
- "chat": {
- "pageTitle": "Grok2API - Chat 聊天",
- "title": "Chat 聊天",
- "subtitle": "通过 chat 接口与 Grok 进行会话聊天",
- "sessions": "会话",
- "newChat": "新增",
- "collapseSidebar": "折叠",
- "expandSidebar": "展开",
- "sessionList": "会话列表",
- "newSession": "新会话",
- "ready": "就绪",
- "emptyState": "输入一条消息开始对话。",
- "uploadFile": "上传文件",
- "placeholder": "询问任何内容",
- "settings": "设置",
- "send": "发送",
- "temperature": "温度",
- "topP": "Top P",
- "systemPrompt": "System Prompt",
- "systemPromptPlaceholder": "可选,设置系统提示词",
- "fileLabel": "[文件]",
- "compositeContent": "[复合内容]",
- "storageFull": "本地存储空间不足,部分会话未保存",
- "attachmentNoEdit": "附件消息暂不支持编辑",
- "saveEdit": "保存",
- "saveEditTitle": "保存编辑",
- "cancelEdit": "取消",
- "cancelEditTitle": "取消编辑",
- "contentEmpty": "内容不能为空",
- "editMessage": "编辑",
- "editMessageTitle": "编辑消息内容",
- "regenerate": "重新生成",
- "regenerateTitle": "从此处重新生成回复",
- "retryTitle": "重试上一条回答",
- "editAnswer": "编辑",
- "editAnswerTitle": "编辑回答内容",
- "copyAnswer": "复制",
- "copyAnswerTitle": "复制回答内容",
- "feedback": "反馈",
- "feedbackTitle": "反馈到 Grok2API",
- "noContentToCopy": "暂无内容可复制",
- "noChatToRetry": "没有可重试的对话",
- "requestFailedCheck": "请求失败,请检查服务状态",
- "requestFailedStatus": "请求失败: {status}",
- "clickRetry": "点击重试",
- "thinking": "思考中",
- "thinkingSec": "思考 {sec} 秒",
- "thought": "已思考",
- "thinkLabel": "思考",
- "empty": "(空)",
- "toolWebSearch": "网页搜索",
- "toolImageSearch": "图片搜索",
- "toolAgentThink": "思考推理",
- "toolDefault": "工具"
- },
- "imagine": {
- "pageTitle": "Grok2API - Imagine 瀑布流",
- "title": "Imagine 瀑布流",
- "subtitle": "通过 WebSocket 持续生成图片,实时展示 base64 瀑布流。",
- "genSettings": "生成设置",
- "prompt": "提示词",
- "promptPlaceholder": "描述你想要的画面,例如:未来城市霓虹雨夜,广角摄影",
- "autoFollow": "自动跟随",
- "autoFollowDesc": "滚动到最新",
- "autoSave": "自动保存",
- "autoSaveDesc": "自动保存图片",
- "aspectRatio": "宽高比",
- "ratio2_3": "2:3 竖图",
- "ratio1_1": "1:1 方图",
- "ratio3_2": "3:2 横图",
- "ratio16_9": "16:9 宽屏",
- "ratio9_16": "9:16 竖屏",
- "concurrent": "并发数量",
- "tasks": "{n} 个任务",
- "concurrentTask1": "1 个任务",
- "concurrentTask2": "2 个任务",
- "concurrentTask3": "3 个任务",
- "autoFilter": "自动过滤",
- "autoFilterDesc": "过滤不达标图片",
- "nsfwLabel": "是否 NSFW",
- "nsfwOn": "开启",
- "nsfwOff": "关闭",
- "saveLocation": "保存位置",
- "browserDefault": "浏览器默认位置",
- "reverseOrder": "反向新增",
- "reverseOrderDesc": "最新显示在上方",
- "connectionStatus": "连接状态",
- "connectionMode": "连接模式",
- "connectionModeAria": "连接模式",
- "imageCount": "图片数量",
- "activeTasks": "活跃任务",
- "avgTime": "平均耗时",
- "gallery": "瀑布流",
- "waitingTitle": "等待连接中",
- "waitingSubtitle": "启动任务后,生成的图片会自动汇聚到这里",
- "start": "开始",
- "batch": "批量",
- "batchDownloadTitle": "批量下载",
- "selectAll": "全选",
- "deselectAll": "取消全选",
- "download": "下载",
- "startedTasks": "已启动 {count} 个并发任务",
- "startedTasksSSE": "已启动 {count} 个并发任务 (SSE)",
- "generatingSSE": "生成中 (SSE)",
- "selectFolder": "已选择文件夹: {name}",
- "selectFolderFailed": "选择文件夹失败",
- "noImagesSelected": "请先选择要下载的图片",
- "jszipFailed": "JSZip 库加载失败,请刷新页面重试",
- "packing": "正在打包 {count} 张图片...",
- "packingBtn": "打包中...",
- "packingProgress": "打包中... ({done}/{total})",
- "noImagesDownloaded": "没有成功获取任何图片",
- "generatingZip": "生成压缩包...",
- "packSuccess": "成功打包 {count} 张图片",
- "packFailed": "打包失败,请重试"
- },
- "video": {
- "pageTitle": "Grok2API - Video 视频生成",
- "title": "Video 视频生成",
- "subtitle": "生成短视频,支持最多 7 张参考图、@图N 引用与多种预设风格。",
- "startGenerate": "开始生成",
- "genSettings": "生成设置",
- "prompt": "提示词",
- "promptPlaceholder": "例如:@图1街头霓虹雨夜,@图2人物回头微笑,慢镜头,胶片质感",
- "promptTip": "多图参考可在提示词中使用 @图1 到 @图7,按参考图顺序对应。",
- "referenceImage": "参考图",
- "referenceImagePlaceholder": "每行一个 https://... 或 data:image/...,最多 7 张",
- "aspectRatio": "画面比例",
- "ratio3_2": "3:2 横构图",
- "ratio2_3": "2:3 竖构图",
- "ratio16_9": "16:9 宽屏",
- "ratio9_16": "9:16 竖屏",
- "ratio1_1": "1:1 方形",
- "duration": "视频时长",
- "seconds": "{n} 秒",
- "resolution": "分辨率",
- "stylePreset": "风格预设",
- "upload": "上传",
- "clearImage": "清除",
- "runStatus": "运行状态",
- "elapsedTime": "耗时 {sec}s",
- "elapsedTimeNone": "耗时 -",
- "metaRatio": "比例",
- "metaDuration": "时长",
- "metaResolution": "分辨率",
- "metaPreset": "预设",
- "videoPreview": "视频预览",
- "clearPreview": "清空",
- "waitingGenerate": "等待生成视频",
- "videoTitle": "视频 {n}",
- "open": "打开",
- "generatingPlaceholder": "生成中…",
- "superResolution": "超分辨率",
- "superResolutionInProgress": "超分辨率中",
- "alreadyGenerating": "已在生成中",
- "referenceConflict": "参考图只能选择其一:URL/Base64 列表 或 本地上传",
- "referenceLimit": "参考图最多支持 7 张",
- "noReferenceSelected": "未选择参考图",
- "downloadFailed": "下载失败,请检查视频链接是否可访问",
- "sec6": "6 秒",
- "sec10": "10 秒",
- "sec15": "15 秒"
- },
- "voice": {
- "pageTitle": "Grok2API - LiveKit 陪聊",
- "title": "LiveKit 陪聊",
- "subtitle": "LiveKit 语音会话,连接 Grok Voice。",
- "startSession": "开始会话",
- "stopSession": "停止会话",
- "connectionSettings": "连接设置",
- "voiceLabel": "声音 (Voice)",
- "personalityLabel": "个性 (Personality)",
- "speedLabel": "语速",
- "settingsHint": "提示:Voice / Personality 会在建立连接前发送到服务端。",
- "sessionLog": "会话日志",
- "clearLog": "清空",
- "copyLog": "复制",
- "sessionStatus": "会话状态",
- "audioOutput": "音频输出",
- "audioHint": "订阅到的音轨会自动插入此区域。",
- "livekitSDKError": "错误: LiveKit SDK 未能正确加载,请刷新页面重试",
- "livekitLoadFailed": "LiveKit SDK 加载失败",
- "secureContextBrowser": "请使用最新版浏览器并允许麦克风权限",
- "secureContextHTTPS": "请使用 HTTPS 或在本机 localhost 访问",
- "secureContextError": "当前环境不支持麦克风权限,{hint}",
- "connectingStatus": "正在连接",
- "fetchingToken": "正在获取 Token...",
- "fetchTokenFailed": "获取 Token 失败: {status}",
- "fetchTokenSuccess": "获取 Token 成功",
- "participantConnected": "参与者已连接: {identity}",
- "participantDisconnected": "参与者已断开: {identity}",
- "trackSubscribed": "订阅音轨: {kind}",
- "disconnected": "已断开连接",
- "connectedToServer": "已连接到 LiveKit 服务器",
- "inCall": "通话中",
- "openingMic": "正在开启麦克风...",
- "voiceEnabled": "语音已开启",
- "voiceConnected": "语音连接成功",
- "errorPrefix": "错误: {msg}",
- "logCopied": "日志已复制",
- "copyLogFailed": "复制失败,请手动选择"
- }
-}
diff --git a/app/assets/js/admin/cache.js b/app/assets/js/admin/cache.js
deleted file mode 100644
index f4e37886..00000000
--- a/app/assets/js/admin/cache.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Cache management — simplified, updated API paths */
-let apiKey = '';
-let currentTab = 'image';
-let listPage = 1;
-const PAGE_SIZE = 100;
-let listData = { image: { items: [], total: 0 }, video: { items: [], total: 0 } };
-
-const byId = id => document.getElementById(id);
-
-async function init() {
- apiKey = await ensureAdminKey();
- if (!apiKey) return;
- setupConfirmDialog();
- loadStats();
-}
-
-async function loadStats() {
- try {
- const res = await fetch(`${API_BASE}/cache`, { headers: buildAuthHeaders(apiKey) });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = await res.json();
- byId('img-count').textContent = data.local_image?.count ?? '-';
- byId('img-size').textContent = data.local_image?.size_mb != null ? data.local_image.size_mb + ' MB' : '-';
- byId('video-count').textContent = data.local_video?.count ?? '-';
- byId('video-size').textContent = data.local_video?.size_mb != null ? data.local_video.size_mb + ' MB' : '-';
- } catch (e) { showToast(e.message, 'error'); }
- loadList();
-}
-
-async function loadList() {
- try {
- const res = await fetch(`${API_BASE}/cache/list?type=${currentTab}&page=${listPage}&page_size=${PAGE_SIZE}`, { headers: buildAuthHeaders(apiKey) });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = await res.json();
- listData[currentTab] = { items: data.items || [], total: data.total || 0 };
- renderList();
- } catch (e) { showToast(e.message, 'error'); }
-}
-
-function renderList() {
- const { items, total } = listData[currentTab];
- const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
- const tbody = byId('file-list-body');
- const empty = byId('file-empty');
- const info = byId('list-info');
- const prev = byId('list-prev');
- const next = byId('list-next');
-
- if (info) info.textContent = `${total === 0 ? 0 : listPage} / ${pages} · ${total}`;
- if (prev) prev.disabled = listPage <= 1;
- if (next) next.disabled = listPage >= pages;
-
- if (!items.length) {
- tbody.replaceChildren();
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
-
- const frag = document.createDocumentFragment();
- items.forEach(f => {
- const tr = document.createElement('tr');
- const sizeKB = f.size_bytes ? (f.size_bytes / 1024).toFixed(1) + ' KB' : '-';
- tr.innerHTML = `
- ${t('common.loading')} ${escapeHtml(f.name)}
- ${sizeKB}
-
-
- `;
- frag.appendChild(tr);
- });
- tbody.replaceChildren(frag);
-}
-
-function switchTab(tab) {
- currentTab = tab; listPage = 1;
- document.querySelectorAll('.tab-item').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
- loadList();
-}
-function listPrev() { if (listPage > 1) { listPage--; loadList(); } }
-function listNext() { const pages = Math.max(1, Math.ceil((listData[currentTab]?.total||0) / PAGE_SIZE)); if (listPage < pages) { listPage++; loadList(); } }
-
-async function deleteFile(name) {
- if (!await confirmAction(`删除文件 ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/cache/item/delete`, {
- method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) },
- body: JSON.stringify({ type: currentTab, name })
- });
- if (res.ok) { showToast('已删除', 'success'); loadStats(); }
- else showToast('删除失败', 'error');
- } catch (e) { showToast(e.message, 'error'); }
-}
-
-async function clearLocalCache() {
- if (!await confirmAction(`清理全部${currentTab === 'image' ? '图片' : '视频'}缓存?`)) return;
- try {
- const res = await fetch(`${API_BASE}/cache/clear`, {
- method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) },
- body: JSON.stringify({ type: currentTab })
- });
- if (res.ok) { showToast('已清理', 'success'); loadStats(); }
- else showToast('清理失败', 'error');
- } catch (e) { showToast(e.message, 'error'); }
-}
-
-window.onload = init;
diff --git a/app/assets/js/admin/config.js b/app/assets/js/admin/config.js
deleted file mode 100644
index 7045b448..00000000
--- a/app/assets/js/admin/config.js
+++ /dev/null
@@ -1,257 +0,0 @@
-let apiKey = '';
-let currentConfig = {};
-const byId = id => document.getElementById(id);
-
-const NUMERIC_FIELDS = new Set([
- 'timeout','max_retry','retry_backoff_base','retry_backoff_factor','retry_backoff_max',
- 'retry_budget','refresh.interval_hours','refresh.super_interval_hours','runtime.fail_threshold',
- 'limit_mb','refresh.on_demand_min_interval_sec','refresh.on_demand_max_tokens',
- 'upload_concurrent','upload_timeout','download_concurrent','download_timeout',
- 'list_concurrent','list_timeout','list_batch_size','delete_concurrent','delete_timeout',
- 'delete_batch_size','reload_interval_sec','stream_timeout','final_timeout',
- 'blocked_grace_seconds','final_min_bytes','medium_min_bytes','blocked_parallel_attempts',
- 'concurrent','batch_size','max_file_size_mb','max_files','request_slow_ms'
-]);
-
-const LOCALE_MAP = {
- app:{label:"应用设置",api_key:{title:"API 密钥",desc:"调用 Grok2API 服务的 Token。"},app_key:{title:"后台密码",desc:"登录管理后台的密码(必填)。"},function_enabled:{title:"启用功能玩法",desc:"是否启用功能玩法入口。"},function_key:{title:"Function 密码",desc:"功能玩法页面的访问密码。"},app_url:{title:"应用地址",desc:"服务外部访问 URL。"},image_format:{title:"图片格式",desc:"默认图片格式。"},video_format:{title:"视频格式",desc:"默认视频格式。"},temporary:{title:"临时对话",desc:"默认启用临时对话。"},disable_memory:{title:"禁用记忆",desc:"默认禁用 Grok 记忆。"},stream:{title:"流式响应",desc:"默认启用流式输出。"},thinking:{title:"思维链",desc:"默认启用思维链。"},dynamic_statsig:{title:"动态指纹",desc:"动态生成 Statsig 指纹。"},custom_instruction:{title:"自定义指令",desc:"透传为 customPersonality。"},filter_tags:{title:"过滤标签",desc:"自动过滤响应中的特殊标签。"}},
- proxy:{label:"代理配置",base_proxy_url:{title:"基础代理 URL",desc:"代理到 Grok 的基础地址。"},asset_proxy_url:{title:"资源代理 URL",desc:"代理到 Grok 的资源地址。"},skip_proxy_ssl_verify:{title:"跳过 SSL 校验",desc:"代理自签名证书时启用。"},enabled:{title:"Managed Clearance",desc:"通过 FlareSolverr 维护 CF clearance。"},flaresolverr_url:{title:"FlareSolverr 地址",desc:"Managed clearance provider 地址。"},refresh_interval:{title:"预热间隔(秒)",desc:"预热间隔,建议≥300。"},timeout:{title:"挑战超时(秒)",desc:"等待解决挑战的最大时间。"},cf_clearance:{title:"CF Clearance",desc:"手动配置的 clearance cookie。"},browser:{title:"浏览器指纹",desc:"curl_cffi 浏览器指纹。"},user_agent:{title:"User-Agent",desc:"HTTP User-Agent。"}},
- retry:{label:"重试策略",max_retry:{title:"最大重试",desc:"最大重试次数。"},retry_status_codes:{title:"重试状态码",desc:"触发重试的 HTTP 状态码。"},reset_session_status_codes:{title:"重建状态码",desc:"触发重建 session 的状态码。"},retry_backoff_base:{title:"退避基数",desc:"基础延迟(秒)。"},retry_backoff_factor:{title:"退避倍率",desc:"指数放大系数。"},retry_backoff_max:{title:"退避上限",desc:"单次最大延迟(秒)。"},retry_budget:{title:"退避预算",desc:"最大重试总耗时(秒)。"}},
- chat:{label:"对话配置",concurrent:{title:"并发上限",desc:"Reverse 并发上限。"},timeout:{title:"请求超时",desc:"超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"}},
- video:{label:"视频配置",enable_public_asset:{title:"公开资产链接",desc:"生成后创建 Public 资产。"},concurrent:{title:"并发上限",desc:"并发上限。"},timeout:{title:"请求超时",desc:"超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"},upscale_timing:{title:"超分时机",desc:"720p 超分模式。"}},
- image:{label:"图像配置",timeout:{title:"请求超时",desc:"WebSocket 超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"},final_timeout:{title:"最终图超时",desc:"等待最终图的超时。"},blocked_grace_seconds:{title:"审查宽限",desc:"判定审查的宽限秒数。"},nsfw:{title:"NSFW 模式",desc:"启用 NSFW。"},medium_min_bytes:{title:"中等图最小字节",desc:"中等图最小字节数。"},final_min_bytes:{title:"最终图最小字节",desc:"最终图最小字节数。"},blocked_parallel_enabled:{title:"并行补偿",desc:"审查时并行补偿。"},blocked_parallel_attempts:{title:"补偿次数",desc:"补偿并发次数。"}},
- imagine_fast:{label:"Imagine Fast",n:{title:"生成数量",desc:"生成数量。"},size:{title:"图片尺寸",desc:"尺寸。"},response_format:{title:"响应格式",desc:"返回格式。"}},
- asset:{label:"资产配置",upload_concurrent:{title:"上传并发",desc:"上传最大并发。"},upload_timeout:{title:"上传超时",desc:"超时(秒)。"},download_concurrent:{title:"下载并发",desc:"下载最大并发。"},download_timeout:{title:"下载超时",desc:"超时(秒)。"},list_concurrent:{title:"查询并发",desc:"查询最大并发。"},list_timeout:{title:"查询超时",desc:"超时(秒)。"},list_batch_size:{title:"查询批次",desc:"单次批次大小。"},delete_concurrent:{title:"删除并发",desc:"删除最大并发。"},delete_timeout:{title:"删除超时",desc:"超时(秒)。"},delete_batch_size:{title:"删除批次",desc:"单次批次大小。"}},
- voice:{label:"语音配置",timeout:{title:"请求超时",desc:"超时(秒)。"}},
- account:{label:"Account 配置","runtime.consumed_mode_enabled":{title:"消耗模式",desc:"按 consumed 选号。"},"runtime.fail_threshold":{title:"失败阈值",desc:"连续失败阈值。"},"refresh.enabled":{title:"刷新调度",desc:"启用周期 refresh。"},"refresh.interval_hours":{title:"普通池间隔",desc:"普通池刷新间隔(小时)。"},"refresh.super_interval_hours":{title:"Super 池间隔",desc:"Super 池间隔(小时)。"},"refresh.on_demand_enabled":{title:"按需刷新",desc:"允许按需 refresh。"},"refresh.on_demand_min_interval_sec":{title:"按需最小间隔",desc:"最小间隔(秒)。"},"refresh.on_demand_max_tokens":{title:"按需最大数量",desc:"最多检查账号数。"}},
- log:{label:"日志配置",max_file_size_mb:{title:"单文件上限",desc:"上限(MB)。"},max_files:{title:"保留数",desc:"最多保留日志文件数。"},log_health_requests:{title:"记录健康检查",desc:"记录 /health。"},log_all_requests:{title:"记录全部请求",desc:"全部请求日志。"},request_slow_ms:{title:"慢请求阈值",desc:"阈值(毫秒)。"}},
- cache:{label:"缓存管理",enable_auto_clean:{title:"自动清理",desc:"自动清理缓存。"},limit_mb:{title:"清理阈值",desc:"阈值(MB)。"}},
- nsfw:{label:"NSFW 配置",concurrent:{title:"并发上限",desc:"并发上限。"},batch_size:{title:"批次大小",desc:"批次大小。"},timeout:{title:"请求超时",desc:"超时(秒)。"}},
- usage:{label:"Usage 配置",concurrent:{title:"并发上限",desc:"并发上限。"},batch_size:{title:"批次大小",desc:"批次大小。"},timeout:{title:"请求超时",desc:"超时(秒)。"}}
-};
-
-const SECTION_ORDER = new Map(Object.keys(LOCALE_MAP).map((k,i) => [k,i]));
-const MANAGED_LOCKED = ['cf_clearance','browser','user_agent'];
-const MANAGED_PROVIDER = ['flaresolverr_url','refresh_interval','timeout'];
-
-function getText(s, k) {
- let ti = t('config.fields.'+s+'.'+k+'.title');
- let de = t('config.fields.'+s+'.'+k+'.desc');
- if (!ti.startsWith('config.fields.')) return {title:ti, desc: de.startsWith('config.fields.') ? '' : de};
- const m = LOCALE_MAP[s]; return m?.[k] || {title: k.replace(/_/g,' '), desc:''};
-}
-function getSectionLabel(s) {
- let l = t('config.sections.'+s);
- return l.startsWith('config.sections.') ? (LOCALE_MAP[s]?.label || s) : l;
-}
-function sortByOrder(keys, order) {
- if (!order) return keys;
- return keys.sort((a,b) => {
- const ia = order.get(a), ib = order.get(b);
- if (ia !== undefined && ib !== undefined) return ia - ib;
- if (ia !== undefined) return -1;
- if (ib !== undefined) return 1;
- return 0;
- });
-}
-
-function setMeta(input, section, key) { input.dataset.section = section; input.dataset.key = key; }
-
-function buildBool(s, k, val) {
- const label = document.createElement('label');
- label.className = 'toggle';
- const input = document.createElement('input');
- input.type = 'checkbox'; input.checked = val; input.className = 'sr-only';
- setMeta(input, s, k);
- const track = document.createElement('div');
- track.className = 'toggle-track';
- label.append(input, track);
- return {input, node: label};
-}
-
-function buildSelect(s, k, val, opts) {
- const input = document.createElement('select');
- input.className = 'input'; setMeta(input, s, k);
- opts.forEach(o => {
- const opt = document.createElement('option');
- opt.value = o.val; opt.text = o.text;
- if (val === o.val) opt.selected = true;
- input.appendChild(opt);
- });
- return {input, node: input};
-}
-
-function buildJson(s, k, val) {
- const input = document.createElement('textarea');
- input.className = 'input font-mono'; input.rows = 4;
- input.value = JSON.stringify(val, null, 2);
- setMeta(input, s, k); input.dataset.type = 'json';
- return {input, node: input};
-}
-
-function buildText(s, k, val) {
- const input = document.createElement('input');
- input.type = 'text'; input.className = 'input'; input.value = val;
- setMeta(input, s, k);
- return {input, node: input};
-}
-
-function buildTextarea(s, k, val, rows=5) {
- const input = document.createElement('textarea');
- input.className = 'input'; input.rows = rows; input.value = val||'';
- setMeta(input, s, k);
- return {input, node: input};
-}
-
-function randomKey(len) {
- const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- const buf = new Uint8Array(len);
- crypto.getRandomValues(buf);
- return Array.from(buf, b => chars[b % chars.length]).join('');
-}
-
-function buildSecret(s, k, val) {
- const input = document.createElement('input');
- input.type = 'text'; input.className = 'input'; input.value = val; input.style.flex = '1';
- setMeta(input, s, k);
- const wrap = document.createElement('div');
- wrap.className = 'flex gap-2';
- const genBtn = document.createElement('button');
- genBtn.className = 'btn btn-primary btn-icon'; genBtn.type = 'button'; genBtn.title = '生成';
- genBtn.innerHTML = '';
- genBtn.onclick = () => { input.value = randomKey(16); };
- const copyBtn = document.createElement('button');
- copyBtn.className = 'btn btn-primary btn-icon'; copyBtn.type = 'button';
- copyBtn.innerHTML = '';
- copyBtn.onclick = () => copyToClipboard(input.value, copyBtn);
- wrap.append(input, genBtn, copyBtn);
- return {input, node: wrap};
-}
-
-function buildFieldCard(section, key, val) {
- const text = getText(section, key);
- const card = document.createElement('div');
- card.className = 'config-field';
- const title = document.createElement('div');
- title.className = 'config-field-title'; title.textContent = text.title;
- card.appendChild(title);
- if (text.desc) {
- const desc = document.createElement('p');
- desc.className = 'config-field-desc'; desc.textContent = text.desc;
- card.appendChild(desc);
- }
- const inputWrap = document.createElement('div');
- inputWrap.className = 'config-field-input';
-
- let built;
- if (section === 'app' && key === 'custom_instruction') built = buildTextarea(section, key, val, 6);
- else if (typeof val === 'boolean') built = buildBool(section, key, val);
- else if (key === 'image_format') built = buildSelect(section, key, val, [{val:'url',text:'URL'},{val:'base64',text:'Base64'}]);
- else if (key === 'video_format') built = buildSelect(section, key, val, [{val:'html',text:'HTML'},{val:'url',text:'URL'}]);
- else if (section==='video' && key==='upscale_timing') built = buildSelect(section, key, val, [{val:'single',text:'single'},{val:'complete',text:'complete'}]);
- else if (section==='imagine_fast' && key==='size') built = buildSelect(section, key, val, [{val:'1024x1024',text:'1024x1024'},{val:'1280x720',text:'1280x720'},{val:'720x1280',text:'720x1280'},{val:'1792x1024',text:'1792x1024'},{val:'1024x1792',text:'1024x1792'}]);
- else if (section==='imagine_fast' && key==='response_format') built = buildSelect(section, key, val, [{val:'url',text:'URL'},{val:'b64_json',text:'B64 JSON'},{val:'base64',text:'Base64'}]);
- else if (Array.isArray(val) || typeof val === 'object') built = buildJson(section, key, val);
- else if (['api_key','app_key','function_key'].includes(key)) built = buildSecret(section, key, val);
- else built = buildText(section, key, val);
-
- if (built) inputWrap.appendChild(built.node);
- card.appendChild(inputWrap);
-
- if (section==='proxy' && key==='enabled' && built) {
- built.input.addEventListener('change', () => applyManagedState(built.input.checked));
- }
- if (section==='app' && key==='function_enabled') {
- card.classList.add('has-action');
- const link = document.createElement('a');
- link.href = '/login'; link.className = 'btn btn-primary btn-icon'; link.title = '访问';
- link.innerHTML = '';
- link.style.display = val ? 'inline-flex' : 'none';
- card.appendChild(link);
- if (built) built.input.addEventListener('change', () => { link.style.display = built.input.checked ? 'inline-flex' : 'none'; });
- }
- return card;
-}
-
-function applyManagedState(enabled) {
- function setDisabled(k, disabled) {
- const el = document.querySelector(`[data-section="proxy"][data-key="${k}"]`);
- if (!el) return;
- el.disabled = disabled;
- const field = el.closest('.config-field');
- if (field) { field.style.opacity = disabled ? '.45' : ''; field.style.pointerEvents = disabled ? 'none' : ''; }
- }
- MANAGED_LOCKED.forEach(k => setDisabled(k, !!enabled));
- MANAGED_PROVIDER.forEach(k => setDisabled(k, !enabled));
-}
-
-function renderConfig(data) {
- const container = byId('config-container');
- if (!container) return;
- container.replaceChildren();
- const frag = document.createDocumentFragment();
- sortByOrder(Object.keys(data), SECTION_ORDER).forEach(section => {
- const items = data[section];
- const localeSection = LOCALE_MAP[section];
- const keyOrder = localeSection ? new Map(Object.keys(localeSection).map((k,i) => [k,i])) : null;
- const keys = sortByOrder(Object.keys(items), keyOrder).filter(k => !(section==='proxy' && k==='cf_cookies'));
- if (!keys.length) return;
- const card = document.createElement('div');
- card.className = 'config-section';
- card.innerHTML = `
-
- ${escapeHtml(item.pool)}
- ${item.status}${nsfwBadge}
- ${consumedModeEnabled ? (item.consumed||0) : (item.quota||0)}
- ${escapeHtml(item.note||'-')}
- `;
- frag.appendChild(tr);
- });
- tbody.replaceChildren(frag);
- updateSelectionState();
-}
-
-/* Selection */
-function toggleSelectAll() { const cb = byId('select-all'); setSelectedForTokens(getVisibleTokens(), cb?.checked); syncVisibleSelectionUI(cb?.checked); updateSelectionState(); }
-function toggleSelect(idx) { flatTokens[idx]._selected = !flatTokens[idx]._selected; const r = document.querySelector(`#token-table-body tr[data-index="${idx}"]`); if (r) r.classList.toggle('row-selected', flatTokens[idx]._selected); updateSelectionState(); }
-
-function setupSelectAllMenu() {
- document.addEventListener('click', e => { if (!byId('select-all-wrap')?.contains(e.target)) byId('select-all-popover')?.classList.add('hidden'); });
- document.addEventListener('keydown', e => { if (e.key === 'Escape') byId('select-all-popover')?.classList.add('hidden'); });
-}
-
-function handleSelectAllPrimary(e) {
- e?.stopPropagation();
- if (countSelected(flatTokens) > 0) { clearAllSelection(); return; }
- const p = byId('select-all-popover');
- p?.classList.toggle('hidden');
-}
-function selectVisibleAllFromMenu() { setSelectedForTokens(getVisibleTokens(), true); syncVisibleSelectionUI(true); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); }
-function selectAllFilteredFromMenu() { setSelectedForTokens(getFilteredTokens(), true); syncVisibleSelectionUI(true); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); }
-function clearAllSelection() { setSelectedForTokens(flatTokens, false); syncVisibleSelectionUI(false); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); }
-
-function updateSelectionState() {
- const sel = countSelected(flatTokens);
- const vis = getVisibleTokens();
- const visSel = countSelected(vis);
- const cb = byId('select-all');
- if (cb) { cb.checked = vis.length > 0 && visSel === vis.length; cb.indeterminate = visSel > 0 && visSel < vis.length; }
- const label = byId('select-all-label');
- if (label) label.textContent = sel > 0 ? t('token.clearSelection') : t('common.selectAll');
- const trigger = byId('select-all-trigger');
- if (trigger) trigger.classList.toggle('is-active', sel > 0);
- const caret = byId('select-all-caret');
- if (caret) caret.style.display = sel > 0 ? 'none' : 'inline';
- const countEl = byId('selected-count');
- if (countEl) countEl.textContent = sel;
- if (sel > 0) byId('select-all-popover')?.classList.add('hidden');
- setActionButtons(sel);
-}
-
-function setActionButtons(count = null) {
- const c = count ?? countSelected(flatTokens);
- const dis = isBatchProcessing;
- ['btn-batch-export','btn-batch-update','btn-batch-disable','btn-batch-enable','btn-batch-nsfw','btn-batch-delete'].forEach(id => {
- const b = byId(id); if (b) b.disabled = dis || c === 0;
- });
-}
-
-/* Filtering & Pagination */
-function filterByStatus(status) {
- currentFilter = status; currentPage = 1;
- document.querySelectorAll('.tab-item').forEach(t => { t.classList.toggle('active', t.dataset.filter === status); });
- renderTable();
-}
-
-function updatePagination(total, pages) {
- const info = byId('pagination-info');
- if (info) info.textContent = `${total === 0 ? 0 : currentPage} / ${pages} · ${total}`;
- const prev = byId('page-prev'); if (prev) prev.disabled = currentPage <= 1;
- const next = byId('page-next'); if (next) next.disabled = currentPage >= pages;
-}
-function goPrevPage() { if (currentPage > 1) { currentPage--; renderTable(); } }
-function goNextPage() { const p = getPaginationData().pages; if (currentPage < p) { currentPage++; renderTable(); } }
-function changePageSize() { const v = parseInt(byId('page-size')?.value); if (v) { pageSize = v; currentPage = 1; renderTable(); } }
-
-/* CRUD */
-let currentEditIndex = -1;
-function addToken() { openEditModal(-1); }
-
-function openEditModal(idx) {
- currentEditIndex = idx;
- const isNew = idx < 0;
- if (isNew) {
- byId('edit-token-display').value = ''; byId('edit-token-display').disabled = false;
- byId('edit-pool').value = 'ssoBasic'; byId('edit-quota').value = 80; byId('edit-note').value = '';
- document.querySelector('#edit-modal .modal-title').textContent = t('token.addTitle');
- } else {
- const item = flatTokens[idx];
- byId('edit-token-display').value = item.token; byId('edit-token-display').disabled = true;
- byId('edit-pool').value = item.pool;
- byId('edit-quota').value = consumedModeEnabled ? (item.consumed||0) : item.quota;
- byId('edit-note').value = item.note || '';
- document.querySelector('#edit-modal .modal-title').textContent = t('token.editTitle');
- }
- openModal('edit-modal');
-}
-function closeEditModal() { closeModal('edit-modal'); }
-
-async function saveEdit() {
- const pool = byId('edit-pool').value.trim() || 'ssoBasic';
- const quota = parseInt(byId('edit-quota').value) || 0;
- const note = byId('edit-note').value.trim().slice(0, 50);
- if (currentEditIndex >= 0) {
- const item = flatTokens[currentEditIndex];
- item.pool = pool; if (!consumedModeEnabled) item.quota = quota; item.note = note;
- } else {
- const token = byId('edit-token-display').value.trim();
- if (!token) return showToast(t('token.tokenEmpty'), 'error');
- if (flatTokens.some(t => t.token === token)) return showToast(t('token.tokenExists'), 'error');
- flatTokens.push({ token, pool, quota, consumed: 0, note, status: 'active', use_count: 0, tags: [], _selected: false });
- }
- await syncToServer(); closeEditModal(); loadData();
-}
-
-async function deleteToken(idx) {
- if (!await confirmAction(t('token.confirmDelete'), { okText: t('common.delete') })) return;
- flatTokens.splice(idx, 1);
- syncToServer().then(loadData);
-}
-
-async function syncToServer() {
- const data = {};
- flatTokens.forEach(t => {
- if (!data[t.pool]) data[t.pool] = [];
- const p = { token: t.token, status: t.status, quota: t.quota, consumed: t.consumed||0, note: t.note||'', fail_count: t.fail_count||0, use_count: t.use_count||0, tags: t.tags||[] };
- if (t.created_at) p.created_at = t.created_at;
- if (t.last_used_at) p.last_used_at = t.last_used_at;
- if (t.last_fail_at) p.last_fail_at = t.last_fail_at;
- if (t.last_sync_at) p.last_sync_at = t.last_sync_at;
- if (t.last_asset_clear_at) p.last_asset_clear_at = t.last_asset_clear_at;
- if (t.last_fail_reason) p.last_fail_reason = t.last_fail_reason;
- data[t.pool].push(p);
- });
- try {
- const res = await fetch(`${API_BASE}/tokens`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify(data) });
- if (!res.ok) showToast(t('common.saveFailed'), 'error');
- } catch (e) { showToast(e.message, 'error'); }
-}
-
-/* Import/Export */
-function openImportModal() { openModal('import-modal'); }
-function closeImportModal() { closeModal('import-modal', () => { const i = byId('import-text'); if (i) i.value = ''; }); }
-async function submitImport() {
- const pool = byId('import-pool').value.trim() || 'ssoBasic';
- const lines = byId('import-text').value.split('\n');
- lines.forEach(l => { const t = l.trim(); if (t && !flatTokens.some(ft => ft.token === t)) flatTokens.push({ token: t, pool, status: 'active', quota: DEFAULT_QUOTA[pool]||80, consumed: 0, note: '', tags: [], fail_count: 0, use_count: 0, _selected: false }); });
- await syncToServer(); closeImportModal(); loadData();
-}
-function batchExport() {
- const sel = getSelectedTokens();
- if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
- downloadTextFile(sel.map(t => t.token).join('\n')+'\n', `tokens_${new Date().toISOString().slice(0,10)}.txt`);
-}
-
-/* Batch ops */
-async function refreshStatus(token) {
- try {
- const res = await fetch(`${API_BASE}/tokens/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify({ tokens: [token] }) });
- if (res.ok) { showToast(t('token.refreshSuccess'), 'success'); loadData(); }
- else showToast(t('token.refreshFailed'), 'error');
- } catch { showToast(t('token.requestError'), 'error'); }
-}
-
-async function batchUpdate() { await startBatchAsync('refresh', `${API_BASE}/tokens/refresh/async`); }
-async function batchEnableNSFW() {
- const sel = getSelectedTokens();
- if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
- if (!await confirmAction(t('token.nsfwConfirm', { count: sel.length }), { okText: t('token.nsfwEnable') })) return;
- await startBatchAsync('nsfw', `${API_BASE}/tokens/nsfw/enable/async`);
-}
-
-async function startBatchAsync(action, url) {
- if (isBatchProcessing) return showToast(t('common.taskInProgress'), 'info');
- const sel = getSelectedTokens();
- if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
- isBatchProcessing = true; currentBatchAction = action;
- batchTotal = sel.length; batchProcessed = 0;
- updateBatchProgress(); setActionButtons();
- try {
- const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify({ tokens: sel.map(t => t.token) }) });
- const data = await res.json();
- if (!res.ok || data.status !== 'success') throw new Error(data.detail || 'Failed');
- currentBatchTaskId = data.task_id;
- BatchSSE.close(batchEventSource);
- batchEventSource = BatchSSE.open(currentBatchTaskId, apiKey, {
- onMessage: msg => {
- if (msg.type === 'progress' || msg.type === 'snapshot') {
- if (msg.total) batchTotal = msg.total;
- if (msg.processed != null) batchProcessed = msg.processed;
- updateBatchProgress();
- } else if (msg.type === 'done') {
- batchProcessed = batchTotal; updateBatchProgress();
- finishBatch(false); showToast(action === 'nsfw' ? t('token.nsfwDone') : t('token.refreshDone'), 'success');
- closeBatchSSE();
- } else if (msg.type === 'cancelled') {
- finishBatch(true); showToast(t('common.cancelled'), 'info'); closeBatchSSE();
- } else if (msg.type === 'error') {
- finishBatch(true); showToast(msg.error || t('common.unknownError'), 'error'); closeBatchSSE();
- }
- },
- onError: () => { finishBatch(true); showToast(t('common.connectionInterrupted'), 'error'); closeBatchSSE(); }
- });
- } catch (e) { finishBatch(true); showToast(e.message, 'error'); }
-}
-
-function closeBatchSSE() { currentBatchTaskId = null; BatchSSE.close(batchEventSource); batchEventSource = null; }
-function stopBatchRefresh() { if (currentBatchTaskId) { BatchSSE.cancel(currentBatchTaskId, apiKey); closeBatchSSE(); } finishBatch(true); }
-function finishBatch(aborted) { isBatchProcessing = false; currentBatchAction = null; updateBatchProgress(); setActionButtons(); updateSelectionState(); loadData(); }
-
-function updateBatchProgress() {
- const c = byId('batch-progress'), txt = byId('batch-progress-text'), stop = byId('btn-stop-action');
- if (!c) return;
- if (!isBatchProcessing) { c.classList.add('hidden'); stop?.classList.add('hidden'); return; }
- c.classList.remove('hidden'); stop?.classList.remove('hidden');
- if (txt) txt.textContent = batchTotal ? `${Math.floor(batchProcessed/batchTotal*100)}%` : '...';
-}
-
-async function batchDelete() {
- if (isBatchProcessing) return;
- const sel = getSelectedTokens();
- if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
- if (!await confirmAction(t('token.confirmBatchDelete', { count: sel.length }), { okText: t('common.delete') })) return;
- const remove = new Set(sel.map(t => t.token));
- flatTokens = flatTokens.filter(t => !remove.has(t.token));
- await syncToServer(); showToast(t('token.deleteDone'), 'success'); loadData();
-}
-
-async function batchSetStatus(target) {
- if (isBatchProcessing) return;
- const sel = getSelectedTokens();
- if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
- const targets = sel.filter(t => t.status !== target);
- if (!targets.length) return;
- const toDisabled = target === 'disabled';
- if (!await confirmAction(t(toDisabled ? 'token.confirmBatchDisable' : 'token.confirmBatchEnable', { count: targets.length }))) return;
- targets.forEach(t => t.status = target);
- await syncToServer(); loadData(); showToast(toDisabled ? t('token.batchDisableDone') : t('token.batchEnableDone'), 'success');
-}
-function batchDisableTokens() { batchSetStatus('disabled'); }
-function batchEnableTokens() { batchSetStatus('active'); }
-
-window.onload = init;
diff --git a/app/assets/js/core/auth.js b/app/assets/js/core/auth.js
deleted file mode 100644
index 0c5ef610..00000000
--- a/app/assets/js/core/auth.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/* Core auth module — key storage, verification, session management */
-const API_BASE = '/admin/api'; // admin API prefix
-const FN_BASE = '/function'; // function API prefix
-const APP_KEY_STORAGE = 'grok2api_app_key';
-const FUNCTION_KEY_STORAGE = 'grok2api_function_key';
-const APP_KEY_XOR_PREFIX = 'enc:xor:';
-const APP_KEY_ENC_PREFIX = 'enc:v1:';
-const APP_KEY_SECRET = 'grok2api-admin-key';
-
-let cachedAdminKey = null;
-let cachedFunctionKey = null;
-
-const _enc = new TextEncoder();
-const _dec = new TextDecoder();
-
-function _toB64(bytes) { let s = ''; bytes.forEach(b => s += String.fromCharCode(b)); return btoa(s); }
-function _fromB64(b64) { const s = atob(b64); const a = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) a[i] = s.charCodeAt(i); return a; }
-function _xor(data, key) { const o = new Uint8Array(data.length); for (let i = 0; i < data.length; i++) o[i] = data[i] ^ key[i % key.length]; return o; }
-
-function xorEncrypt(plain) {
- return APP_KEY_XOR_PREFIX + _toB64(_xor(_enc.encode(plain), _enc.encode(APP_KEY_SECRET)));
-}
-function xorDecrypt(stored) {
- if (!stored.startsWith(APP_KEY_XOR_PREFIX)) return stored;
- return _dec.decode(_xor(_fromB64(stored.slice(APP_KEY_XOR_PREFIX.length)), _enc.encode(APP_KEY_SECRET)));
-}
-
-async function _deriveKey(salt) {
- const km = await crypto.subtle.importKey('raw', _enc.encode(APP_KEY_SECRET), 'PBKDF2', false, ['deriveKey']);
- return crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' }, km, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
-}
-
-async function encryptAppKey(plain) {
- if (!plain) return '';
- if (!crypto?.subtle) return xorEncrypt(plain);
- const salt = crypto.getRandomValues(new Uint8Array(16));
- const iv = crypto.getRandomValues(new Uint8Array(12));
- const key = await _deriveKey(salt);
- const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, _enc.encode(plain));
- return `${APP_KEY_ENC_PREFIX}${_toB64(salt)}:${_toB64(iv)}:${_toB64(new Uint8Array(cipher))}`;
-}
-
-async function decryptAppKey(stored) {
- if (!stored) return '';
- if (stored.startsWith(APP_KEY_XOR_PREFIX)) return xorDecrypt(stored);
- if (!stored.startsWith(APP_KEY_ENC_PREFIX)) return stored;
- if (!crypto?.subtle) return '';
- const parts = stored.split(':');
- if (parts.length !== 5) return '';
- const [, , saltB64, ivB64, cipherB64] = parts;
- const key = await _deriveKey(_fromB64(saltB64));
- return _dec.decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: _fromB64(ivB64) }, key, _fromB64(cipherB64)));
-}
-
-async function getStoredAppKey() {
- const s = localStorage.getItem(APP_KEY_STORAGE) || '';
- if (!s) return '';
- try { return await decryptAppKey(s); } catch { clearStoredAppKey(); return ''; }
-}
-
-async function getStoredFunctionKey() {
- const s = localStorage.getItem(FUNCTION_KEY_STORAGE) || '';
- if (!s) return '';
- try { return await decryptAppKey(s); } catch { clearStoredFunctionKey(); return ''; }
-}
-
-async function storeAppKey(key) {
- if (!key) { clearStoredAppKey(); return; }
- localStorage.setItem(APP_KEY_STORAGE, await encryptAppKey(key) || '');
-}
-
-async function storeFunctionKey(key) {
- if (!key) { clearStoredFunctionKey(); return; }
- localStorage.setItem(FUNCTION_KEY_STORAGE, await encryptAppKey(key) || '');
-}
-
-function clearStoredAppKey() { localStorage.removeItem(APP_KEY_STORAGE); cachedAdminKey = null; }
-function clearStoredFunctionKey() { localStorage.removeItem(FUNCTION_KEY_STORAGE); cachedFunctionKey = null; }
-
-async function verifyKey(url, key) {
- const h = key ? { Authorization: `Bearer ${key}` } : {};
- return (await fetch(url, { headers: h })).ok;
-}
-
-async function ensureAdminKey() {
- if (cachedAdminKey) return cachedAdminKey;
- const key = await getStoredAppKey();
- if (!key) { window.location.href = '/admin/login'; return null; }
- try {
- if (!await verifyKey(`${API_BASE}/verify`, key)) throw 0;
- cachedAdminKey = `Bearer ${key}`;
- return cachedAdminKey;
- } catch { clearStoredAppKey(); window.location.href = '/admin/login'; return null; }
-}
-
-async function ensureFunctionKey() {
- if (cachedFunctionKey !== null) return cachedFunctionKey;
- const key = await getStoredFunctionKey();
- if (!key) {
- try { if (await verifyKey(`${FN_BASE}/voice/token`, '')) { cachedFunctionKey = ''; return ''; } } catch {}
- return null;
- }
- try {
- if (!await verifyKey(`${FN_BASE}/voice/token`, key)) throw 0;
- cachedFunctionKey = `Bearer ${key}`;
- return cachedFunctionKey;
- } catch { clearStoredFunctionKey(); return null; }
-}
-
-function buildAuthHeaders(apiKey) { return apiKey ? { Authorization: apiKey } : {}; }
-function logout() { clearStoredAppKey(); clearStoredFunctionKey(); window.location.href = '/admin/login'; }
-function functionLogout() { clearStoredFunctionKey(); window.location.href = '/login'; }
-
-async function fetchStorageType() {
- const apiKey = await ensureAdminKey();
- if (!apiKey) return null;
- try {
- const r = await fetch(`${API_BASE}/storage`, { headers: buildAuthHeaders(apiKey) });
- if (!r.ok) return null;
- const d = await r.json();
- return d?.type || null;
- } catch { return null; }
-}
-
-function formatStorageLabel(type) {
- if (!type) return '-';
- const map = { local: 'local', mysql: 'mysql', pgsql: 'pgsql', postgres: 'pgsql', postgresql: 'pgsql', redis: 'redis' };
- return map[type.toLowerCase()] || '-';
-}
diff --git a/app/assets/js/core/header.js b/app/assets/js/core/header.js
deleted file mode 100644
index cc150a96..00000000
--- a/app/assets/js/core/header.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/* Unified header injection — handles both admin and function pages */
-(function() {
- const GITHUB_ICON = '';
-
- var ADMIN_NAV = `
- Token管理
- 配置管理
- 缓存管理`;
-
- var ADMIN_RIGHT = `
-
-
- 反馈
- `;
-
- var FUNCTION_NAV = `
- Chat
- Imagine
- Voice
- Video`;
-
- var FUNCTION_RIGHT = `
-
- `;
-
- var FOOTER_HTML = '';
-
- var container = document.getElementById('app-header');
- if (container && !container.children.length) {
- var type = container.dataset.type || 'admin';
- var isAdmin = type === 'admin';
- container.innerHTML = '
`;
- const token = `@@CODEBLOCK_${codeBlocks.length}@@`;
- codeBlocks.push(html);
- return token;
- });
-
- const renderInline = (value) => {
- const inlineCodes = [];
- let output = value.replace(/`([^`]+)`/g, (match, code) => {
- const token = `@@INLINE_${inlineCodes.length}@@`;
- inlineCodes.push(`${code}${code}`);
- return token;
- });
-
- output = output
- .replace(/\*\*([^*]+)\*\*/g, '$1')
- .replace(/\*([^*]+)\*/g, '$1')
- .replace(/~~([^~]+)~~/g, '$1');
-
- output = output.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => {
- const safeAlt = escapeHtml(alt || 'image');
- if (!isSafeImageUrl(url)) return safeAlt;
- const safeUrl = escapeHtml(url || '');
- return ``;
- });
-
- output = output.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => {
- const safeLabel = escapeHtml(label || '');
- if (!isSafeLinkUrl(url)) return safeLabel;
- const safeUrl = escapeHtml(url || '');
- return `${safeLabel}`;
- });
-
- output = output.replace(/(data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)/g, (match, uri) => {
- if (!isSafeImageUrl(uri)) return '';
- const safeUrl = escapeHtml(uri || '');
- return `
`;
- });
-
- inlineCodes.forEach((html, i) => {
- output = output.replace(new RegExp(`@@INLINE_${i}@@`, 'g'), html);
- });
-
- return output;
- };
-
- const lines = fenced.split(/\r?\n/);
- const htmlParts = [];
- let inUl = false;
- let inUlTask = false;
- let inOl = false;
- let inTable = false;
- let paragraphLines = [];
-
- const closeLists = () => {
- if (inUl) {
- htmlParts.push('');
- inUl = false;
- inUlTask = false;
- }
- if (inOl) {
- htmlParts.push('');
- inOl = false;
- }
- };
-
- const closeTable = () => {
- if (inTable) {
- htmlParts.push('');
- inTable = false;
- }
- };
-
- const flushParagraph = () => {
- if (!paragraphLines.length) return;
- const joined = paragraphLines.join('
');
- htmlParts.push(`
');
- continue;
- }
-
- if (/^\s*>/.test(line)) {
- flushParagraph();
- closeLists();
- closeTable();
- const quoteLines = [];
- let j = i;
- for (; j < lines.length; j += 1) {
- const currentLine = lines[j];
- if (!/^\s*>/.test(currentLine)) break;
- quoteLines.push(currentLine.replace(/^\s*>\s?/, ''));
- }
- i = j - 1;
- const quoteText = quoteLines.join('\n');
- htmlParts.push(`${renderBasicMarkdown(quoteText)}
`);
- continue;
- }
-
- if (trimmed.includes('|')) {
- const nextLine = lines[i + 1] || '';
- if (!inTable && isTableSeparator(nextLine.trim())) {
- flushParagraph();
- closeLists();
- const headers = splitTableRow(trimmed);
- htmlParts.push('');
- headers.forEach(cell => htmlParts.push(` ');
- inTable = true;
- i += 1;
- continue;
- }
- if (inTable && !isTableSeparator(trimmed)) {
- const cells = splitTableRow(trimmed);
- htmlParts.push('${renderInline(cell)} `));
- htmlParts.push('');
- cells.forEach(cell => htmlParts.push(` ');
- continue;
- }
- }
-
- const taskMatch = trimmed.match(/^[-*+•·]\s+\[([ xX])\]\s+(.*)$/);
- if (taskMatch) {
- flushParagraph();
- if (inUl && !inUlTask) {
- closeLists();
- }
- if (!inUl) {
- closeLists();
- closeTable();
- htmlParts.push('${renderInline(cell)} `));
- htmlParts.push('');
- inUl = true;
- inUlTask = true;
- }
- const checked = taskMatch[1].toLowerCase() === 'x';
- htmlParts.push(`
');
- inUl = true;
- inUlTask = false;
- }
- htmlParts.push(`
');
- inOl = true;
- }
- htmlParts.push(`
${title}
${title}
${t('chat.thinkLabel')}