Commit Graph

434 Commits

Author SHA1 Message Date
Xiangyuan-liu
7b29f429ee refactor: log params and channel params
refactor: log params and channel params
2025-07-07 14:26:37 +08:00
Calcium-Ion
5ec421d8e6 Merge pull request #1321 from iszcz/main
支持Midjourney视频任务和图片编辑
2025-07-05 15:28:33 +08:00
CaIon
7e298f8ad1 feat: refactor environment variable initialization and introduce new constant types for API and context keys 2025-07-03 13:10:25 +08:00
CaIon
389a4c3e4c Merge branch 'main' into alpha 2025-07-01 13:15:47 +08:00
iszcz
660180ea1b 支持Midjourney视频任务和图片编辑 2025-06-30 22:31:12 +08:00
Xiangyuan-liu
76da067d40 feat: 优化分页组件 2025-06-25 18:42:19 +08:00
t0ng7u
093d86040f 🗑️ feat(token): implement batch token deletion API & front-end integration
• Back-end
  • model/token.go
    • Add `BatchDeleteTokens(ids []int, userId int)` – transactional DB removal + async Redis cache cleanup.
  • controller/token.go
    • Introduce `TokenBatch` DTO and `DeleteTokenBatch` handler calling the model layer; returns amount deleted.
  • router/api-router.go
    • Register `POST /api/token/batch` route (user-scoped).

• Front-end (TokensTable.js)
  • Replace per-token deletion loops with single request to `/api/token/batch`.
  • Display dynamic i18n message: “Deleted {{count}} tokens!”.
  • Add modal confirmation:
    • Title “Batch delete token”.
    • Content “Are you sure you want to delete the selected {{count}} tokens?”.
  • UI/UX tweaks
    • Responsive button group (flex-wrap, mobile line-break).
    • Clear `selectedKeys` after refresh / successful deletion to avoid ghost selections.

• i18n
  • Ensure placeholder style matches translation keys (`{{count}}`).

This commit delivers efficient, scalable token management and an improved user experience across devices.
2025-06-22 16:35:30 +08:00
Calcium-Ion
03468e05e4 Merge pull request #1267 from t0ng7u/feature/upstream-ratio-sync
🔄 feat(ratio-sync): introduce upstream ratio synchronisation feature #1220
2025-06-20 16:22:00 +08:00
CaIon
f978d8224e feat: add data presence check before batch update in utils 2025-06-19 19:34:57 +08:00
creamlike1024
2b7dff2d94 fix: 使用日志分组查询 2025-06-19 17:17:32 +08:00
Apple\Apple
7975cdf3bf 🚀 feat(ratio-sync): major refactor & UX overhaul for Upstream Ratio Sync 2025-06-19 08:57:34 +08:00
creamlike1024
9708d645d3 feat: 充值方式设置 2025-06-18 21:23:06 +08:00
Apple\Apple
a180d13182 🚚 Refactor(ratio_setting): refactor ratio management into standalone ratio_setting package
Summary
• Migrated all ratio-related sources into `setting/ratio_setting/`
  – `model_ratio.go` (renamed from model-ratio.go)
  – `cache_ratio.go`
  – `group_ratio.go`
• Changed package name to `ratio_setting` and relocated initialization (`ratio_setting.InitRatioSettings()` in main).
• Updated every import & call site:
  – Model / cache / completion / image ratio helpers
  – Group ratio helpers (`GetGroupRatio*`, `ContainsGroupRatio`, `CheckGroupRatio`, etc.)
  – JSON-serialization & update helpers (`*Ratio2JSONString`, `Update*RatioByJSONString`)
• Adjusted controllers, middleware, relay helpers, services and models to reference the new package.
• Removed obsolete `setting` / `operation_setting` imports; added missing `ratio_setting` imports.
• Adopted idiomatic map iteration (`for key := range m`) where value is unused.
• Ran static checks to ensure clean build.

This commit centralises all ratio configuration (model, cache and group) in one cohesive module, simplifying future maintenance and improving code clarity.
2025-06-18 18:00:49 +08:00
Apple\Apple
547da2da60 🚀 feat(Channels): Enhance Channel Filtering & Performance
feat(api):
• Add optional `type` query param to `/api/channel` endpoint for type-specific pagination
• Return `type_counts` map with counts for each channel type
• Implement `GetChannelsByType`, `CountChannelsByType`, `CountChannelsGroupByType` in `model/channel.go`

feat(frontend):
• Introduce type Tabs in `ChannelsTable` to switch between channel types
• Tabs show dynamic counts using backend `type_counts`; “All” is computed from sum
• Persist active type, reload data on tab change (with proper query params)

perf(frontend):
• Use a request counter (`useRef`) to discard stale responses when tabs switch quickly
• Move all `useMemo` hooks to top level to satisfy React Hook rules
• Remove redundant local type counting fallback when backend data present

ui:
• Remove icons from response-time tags for cleaner look
• Use Semi-UI native arrow controls for Tabs; custom arrow code deleted

chore:
• Minor refactor & comments for clarity
• Ensure ESLint Hook rules pass

Result: Channel list now supports fast, accurate type filtering with correct counts, improved concurrency safety, and cleaner UI.
2025-06-18 02:33:18 +08:00
Calcium-Ion
ab627db4be Merge pull request #1239 from QuantumNous/auto_group
feat: auto分组
2025-06-17 21:14:09 +08:00
CaIon
0f35d2368f feat: enhance group ratio handling in pricing calculations 2025-06-17 21:05:35 +08:00
RedwindA
0b9c6ecb00 🔧 refactor(redis): replace direct constant usage with RedisKeyCacheSeconds function for cache duration 2025-06-17 03:24:39 +08:00
creamlike1024
7fa21ce95f feat: auto分组 2025-06-16 22:15:12 +08:00
Apple\Apple
3ac02879de feat: add admin-only "remark" support for users
* backend
  - model: add `Remark` field (varchar 255, `json:"remark,omitempty"`); AutoMigrate handles schema change automatically
  - controller:
    * accept `remark` on user create/update endpoints
    * hide remark from regular users (`GetSelf`) by zero-ing the field before JSON marshalling
    * clarify inline comment explaining the omitempty behaviour

* frontend (React / Semi UI)
  - AddUser.js & EditUser.js: add “Remark” input for admins
  - UsersTable.js:
    * remove standalone “Remark” column
    * show remark as a truncated Tag next to username with Tooltip for full text
    * import Tooltip component
  - i18n: reuse existing translations where applicable

This commit enables administrators to label users with private notes while ensuring those notes are never exposed to the users themselves.
2025-06-16 03:20:54 +08:00
CaIon
ab0ba9f38c feat(database): implement database migration logic for PostgreSQL and add fast migration fallback 2025-06-14 19:47:44 +08:00
Calcium-Ion
e6e5f31921 Merge pull request #1225 from QuantumNous/fix_mixing_sql_conflicts
Fix mixing databases conflicts
2025-06-14 18:24:53 +08:00
CaIon
8978dc7a8b 🐛 fix(log): optimize channel ID collection by using a map to prevent duplicates 2025-06-14 18:23:25 +08:00
CaIon
d57e6425e5 🐛 fix(ability, channel): standardize boolean value handling across database queries 2025-06-14 18:15:45 +08:00
CaIon
b9b4b24961 fix: Resolving conflicts caused by mixing multiple databases 2025-06-14 17:51:05 +08:00
Apple\Apple
c554015526 refactor(console_setting): migrate console settings to model_setting auto-injection
Backend
- Introduce `setting/console_setting` package that defines `ConsoleSetting` struct with JSON tags and validation rules.
- Register the new module with `config.GlobalConfig` to enable automatic injection/export of configuration values.
- Remove legacy `setting/console.go` and the manual `OptionMap` hooks; clean up `model/option.go`.
- Add `controller/console_migrate.go` providing `/api/option/migrate_console_setting` endpoint for one-off data migration.
- Update controllers (`misc`, `option`, `uptime_kuma`) and router to consume namespaced keys `console_setting.*`.

Frontend
- Refactor dashboard pages (`SettingsAPIInfo`, `SettingsAnnouncements`, `SettingsFAQ`, `SettingsUptimeKuma`) and detail page to read/write the new keys.
- Simplify `DashboardSetting.js` state to only include namespaced options.

BREAKING CHANGE: All console-related option keys are now stored under `console_setting.*`. Run the migration endpoint once after deployment to preserve existing data.
2025-06-14 00:40:29 +08:00
Apple\Apple
6c359839cc 🎫 feat: Enhance redemption code expiry handling & improve UI responsiveness
Backend
• Introduced `validateExpiredTime` helper in `controller/redemption.go`; reused in both Add & Update endpoints to enforce “expiry time must not be earlier than now”, eliminating duplicated checks
• Removed `RedemptionCodeStatusExpired` constant and all related references – expiry is now determined exclusively by the `expired_time` field for simpler, safer state management
• Simplified `DeleteInvalidRedemptions`: deletes codes that are `used` / `disabled` or `enabled` but already expired, without relying on extra status codes
• Controller no longer mutates `status` when listing or fetching redemption codes; clients derive expiry status from timestamp

Frontend
• Added reusable `isExpired` helper in `RedemptionsTable.js`; leveraged for:
  – status rendering (orange “Expired” tag)
  – action-menu enable/disable logic
  – row styling
• Removed duplicated inline expiry logic, improving readability and performance
• Adjusted toolbar layout: on small screens the “Clear invalid codes” button now wraps onto its own line, while “Add” & “Copy” remain grouped

Result
The codebase is now more maintainable, secure, and performant with no redundant constants, centralized validation, and cleaner UI behaviour across devices.
2025-06-13 20:51:20 +08:00
Apple\Apple
47531a6b93 feat(ui): add incremental-add feedback & translations for model lists (#1218)
Front-end enhancements around “Add custom models”:

• EditChannel.js / EditTagModal.js
  – Skip models that already exist instead of blocking the action.
  – Collect actually inserted items and display:
      • Success toast: “Added N models: model1, model2 …”
      • Info toast when no new model detected.
  – Keeps UX smooth while preserving deduplication logic.

• i18n
  – en.json: added keys
      • "已新增 {{count}} 个模型:{{list}}"
      • "未发现新增模型"
  – Fixed a broken JSON string containing smart quotes to maintain valid syntax.

Result:
Users can bulk-paste model names; duplicates are silently ignored and the UI clearly lists what was incrementally appended. All messages are fully internationalised.

Closes #1218
2025-06-13 13:49:15 +08:00
Apple\Apple
034cc7f118 🐛 fix(ability): keep case-sensitive (group, model) keys during deduplication
The previous patch lower-cased `group` and `model` when building the
temporary `abilitySet` used to prevent duplicate inserts.
This merged models that differ only by letter case, e.g.
`GPT-3.5-turbo` vs `gpt-3.5-turbo`, causing them to disappear from the
user’s available-models list and pricing page.

Change:
• ability.go – removed all `strings.ToLower` calls when composing the
  deduplication key (`group|model`), so duplicates are checked in a
  case-sensitive manner while preserving the original data.

Result:
• `GPT-3.5-turbo` and `gpt-3.5-turbo` are now treated as distinct
  models throughout the system.
2025-06-13 13:03:06 +08:00
Apple\Apple
927cd07a3f 🐛 fix(ability): prevent duplicate (group, model) pairs when saving channels
When importing large model lists (≈700+) an attempt to save a channel
could fail with:

    Error 1062 (23000): Duplicate entry 'default-DeepSeek-1' for key 'abilities.PRIMARY'

Root cause: AddAbilities / UpdateAbilities inserted the same
(group, model) pair multiple times if the input list contained
duplicates or case-variants (e.g. `default` vs `Default`).

Changes:
• ability.go
  – AddAbilities: introduced `abilitySet` to deduplicate by
    lower-cased `group|model` key before batch-inserting.
  – UpdateAbilities: applied the same deduplication logic when
    rebuilding abilities inside a transaction.

Notes:
• The lower-casing is only for set comparison; the original
  `group` and `model` values are preserved when persisting to DB,
  so case sensitivity of stored data is unchanged.
• Batch chunking logic (lo.Chunk) and performance characteristics
  remain unaffected.

Fixes #1215
2025-06-13 12:39:54 +08:00
Apple\Apple
a8a2141626 Merge remote-tracking branch 'origin/alpha' into alpha 2025-06-13 01:34:26 +08:00
Apple\Apple
0401f1e9ec 🔒 feat: Add user-configurable IP logging for consume and error logs
- Add IP field to Log model with database index and default empty value
- Implement conditional IP recording based on user setting in RecordConsumeLog and RecordErrorLog
- Add UserSettingRecordIpLog constant and update user settings API to handle record_ip_log field
- Create dedicated "IP记录" tab in personal settings under "其他设置" section
- Add IP column to logs table with help tooltip explaining recording conditions
- Make IP column visible to all users (not admin-only) with proper filtering for consume/error log types
- Restrict display of use_time and retry columns to consume and error log types only
- Update personal settings UI structure: rename "通知设置" to "其他设置" to accommodate new functionality
- Add proper translation support and maintain consistent styling across components

The IP logging feature is disabled by default and only records client IP addresses
for consume (type 2) and error (type 5) logs when explicitly enabled by users
in their personal settings.
2025-06-13 01:34:01 +08:00
Calcium-Ion
358af20ad1 Merge pull request #1207 from QuantumNous/user_group_ratio
feat: 分组特殊倍率
2025-06-13 01:25:46 +08:00
Apple\Apple
dcefd7dfb4 🚀 feat(pagination): unify backend-driven pagination & improve channel tag aggregation
SUMMARY
• Migrated Token, Task, Midjourney, Channel, Redemption tables to true server-side pagination.
• Added total / page / page_size metadata in API responses; switched all affected React tables to consume new structure.
• Implemented counting helpers:
  – model/token.go CountUserTokens
  – model/task.go TaskCountAllTasks / TaskCountAllUserTask
  – model/midjourney.go CountAllTasks / CountAllUserTask
  – model/channel.go CountAllChannels / CountAllTags
• Refactored controllers (token, task, midjourney, channel) for 1-based paging & aggregated returns.
• Redesigned `ChannelsTable.js`:
  – `loadChannels`, `syncPageData`, `enrichChannels` for tag-mode grouping without recursion.
  – Fixed runtime white-screen (maximum call-stack) by removing child duplication.
  – Pagination, search, tag-mode, idSort all hot-reload correctly.
• Removed unused `log` import in controller/midjourney.go.

BREAKING CHANGES
Front-end consumers must now expect data.items / total / page / page_size from list endpoints (`/api/channel`, `/api/task`, `/api/mj`, `/api/token`, etc.).
2025-06-12 17:25:25 +08:00
creamlike1024
a28ab3628a feat: 分组特殊倍率 2025-06-11 23:46:59 +08:00
Apple\Apple
52356a1b92 ⏱️ feat: implement uptime monitoring
Introduce application uptime monitoring to improve observability and reliability.

• Add UptimeService to track process start time and expose uptime in seconds
• Create /health/uptime endpoint returning the current uptime in JSON format
• Integrate uptime metric into existing health-check middleware
• Update README with instructions for consuming the new endpoint
• Add unit tests covering UptimeService and new health route

This change enables operations teams and dashboards to programmatically
determine how long the service has been running, facilitating automated
alerts and trend analysis.
2025-06-11 02:28:36 +08:00
Apple\Apple
768ab854d6 feat: major refactor and enhancement of Detail dashboard component & add api url display
- **Code Organization & Architecture:**
  - Restructured component with clear sections (Hooks, Constants, Helper Functions, etc.)
  - Added comprehensive code organization comments for better maintainability
  - Extracted reusable helper functions and constants for better separation of concerns

- **Performance Optimizations:**
  - Implemented extensive use of useCallback and useMemo hooks for expensive operations
  - Optimized data processing pipeline with dedicated processing functions
  - Memoized chart configurations, performance metrics, and grouped stats data
  - Cached helper functions like getTrendSpec, handleCopyUrl, and modal handlers

- **UI/UX Enhancements:**
  - Added Empty state component with construction illustrations for better UX
  - Implemented responsive grid layout with conditional API info section visibility
  - Enhanced button styling with consistent rounded design and hover effects
  - Added mini trend charts to statistics cards for visual data representation
  - Improved form field consistency with reusable createFormField helper

- **Feature Improvements:**
  - Added self-use mode detection to conditionally hide/show API information section
  - Enhanced chart configurations with centralized CHART_CONFIG constant
  - Improved time handling with dedicated helper functions (getTimeInterval, getInitialTimestamp)
  - Added comprehensive performance metrics calculation (RPM/TPM trends)
  - Implemented advanced data aggregation and processing workflows

- **Code Quality & Maintainability:**
  - Extracted complex data processing logic into dedicated functions
  - Added proper prop destructuring and state organization
  - Implemented consistent naming conventions and helper utilities
  - Enhanced error handling and loading states management
  - Added comprehensive JSDoc-style comments for better code documentation

- **Technical Debt Reduction:**
  - Replaced repetitive form field definitions with reusable components
  - Consolidated chart update logic into centralized updateChartSpec function
  - Improved data flow with better state management patterns
  - Reduced code duplication through strategic use of helper functions

This refactor significantly improves component performance, maintainability, and user experience while maintaining backward compatibility and existing functionality.
2025-06-09 17:44:23 +08:00
RedwindA
eff9ce117f refactor: rename RedisHDelObj to RedisDelKey and update references 2025-06-05 21:17:57 +08:00
CaIon
c53a48cde5 feat: add panic recovery and retry mechanism for InitChannelCache; improve batch deletion of abilities in FixAbility 2025-05-23 01:26:52 +08:00
creamlike1024
3d4bd76083 feat: add option to allow worker HTTP image requests 2025-05-09 02:00:42 +08:00
creamlike1024
7c29844e4a Merge branch 'tbphp_model_request_rate_limit_for_group' of github.com:tbphp/new-api into tbphp-tbphp_model_request_rate_limit_for_group 2025-05-08 23:16:06 +08:00
skynono
0cf4c59d22 feat: add original password verification when changing password 2025-05-06 14:28:27 +08:00
tbphp
87188cd7d4 fix: 缩进修复还原 2025-05-05 23:53:05 +08:00
tbphp
1513ed7847 refactor: 调整代码,符合项目现有规范 2025-05-05 19:32:22 +08:00
tbphp
7e7d6112ca feat: 优化代码,去除多余注释和修改 2025-05-05 11:34:57 +08:00
tbphp
6c3fb7777e feat: 增加分组速率功能 2025-05-05 07:31:54 +08:00
CaIon
da6423de33 refactor: Reducing the lock duration to the minimum necessary time in CacheGetRandomSatisfiedChannel function 2025-04-29 15:57:21 +08:00
IcedTangerine
c412fd9cde Merge pull request #1008 from JoeyLearnsToCode/feat-search-channel-by-url
feat: support searching channels by base url
2025-04-28 13:15:49 +08:00
JoeyLearnsToCode
a9b9d23586 feat: support searching channels by base url 2025-04-28 11:38:53 +08:00
wzxjohn
2bd2d73d33 feat: improve log delete api 2025-04-28 11:25:04 +08:00
creamlike1024
62da481dc6 Merge branch 'error-logs' of github.com:zenghongtu/new-api into zenghongtu-error-logs 2025-04-28 11:06:32 +08:00