diff --git a/client/lib/l10n/app_text.dart b/client/lib/l10n/app_text.dart index acf8a28..57aecf9 100644 --- a/client/lib/l10n/app_text.dart +++ b/client/lib/l10n/app_text.dart @@ -95,6 +95,9 @@ abstract class AppText { String get devNeverLogin; String get devForceLogout; String get devClearLogin; + String get devRename; + String get devRenameHint; + String get devSave; String get devForceLogoutConfirm; // 弹窗正文(含设备名占位 %s) String get devClearLoginConfirm; String get devCancel; diff --git a/client/lib/l10n/strings_en.dart b/client/lib/l10n/strings_en.dart index d54aeeb..72f27e8 100644 --- a/client/lib/l10n/strings_en.dart +++ b/client/lib/l10n/strings_en.dart @@ -140,6 +140,12 @@ class StringsEn extends AppText { @override String get devClearLogin => 'Clear login info'; @override + String get devRename => 'Rename'; + @override + String get devRenameHint => 'Device name'; + @override + String get devSave => 'Save'; + @override String get devForceLogoutConfirm => 'This revokes the device\'s login session — it will be kicked offline and must sign in again. The device stays in the list.'; @override String get devClearLoginConfirm => 'This removes the device from the list entirely and revokes its login session and data-plane credential. The device must sign in again to be used.'; diff --git a/client/lib/l10n/strings_zh.dart b/client/lib/l10n/strings_zh.dart index f803a52..2d8a40e 100644 --- a/client/lib/l10n/strings_zh.dart +++ b/client/lib/l10n/strings_zh.dart @@ -139,6 +139,12 @@ class StringsZh extends AppText { @override String get devClearLogin => '清除登录信息'; @override + String get devRename => '重命名'; + @override + String get devRenameHint => '设备名称'; + @override + String get devSave => '保存'; + @override String get devForceLogoutConfirm => '将吊销该设备的登录会话,它会被踢下线、需重新登录。设备仍保留在列表中。'; @override String get devClearLoginConfirm => '将从设备列表彻底移除此设备,并吊销其登录会话与数据面凭证。该设备需重新登录才能再次使用。'; diff --git a/client/lib/services/account_api.dart b/client/lib/services/account_api.dart index 416f9ed..4fdb832 100644 --- a/client/lib/services/account_api.dart +++ b/client/lib/services/account_api.dart @@ -64,6 +64,11 @@ class AccountApi { await _c.postJson('/v1/me/devices/$uuid/logout'); } + /// POST /v1/me/devices/{uuid}/rename — 重命名设备。 + Future renameDevice(String uuid, String name) async { + await _c.postJson('/v1/me/devices/$uuid/rename', {'name': name}); + } + /// GET /v1/usage?days=N&tz_offset=M — 最近 N 天用量(默认 7,后端范围 [1,90])。 /// 带本机时区偏移(分钟,如 UTC+8=480),服务端按「本地日」聚合 → 「今天」与本地日历一致 /// (修「29 号却显示 28 号数据」的时区 bug)。 diff --git a/client/lib/services/device_identity.dart b/client/lib/services/device_identity.dart index 339f1e4..2d3fb8b 100644 --- a/client/lib/services/device_identity.dart +++ b/client/lib/services/device_identity.dart @@ -103,21 +103,37 @@ class DeviceIdentity { return 'unknown'; } + /// 平台简写(默认名前缀,保持短)。 + static String _shortPlatform(String p) => switch (p) { + 'windows' => 'Win', + 'macos' => 'Mac', + 'linux' => 'Linux', + 'ios' => 'iOS', + 'android' => 'Andr', + _ => p, + }; + + // 默认名 = 平台简写·主机名(桌面用主机名,移动用机型);主机名截到 8、总长≈12,尽量短。 + // 用户可在「我的设备」改名覆盖。 Future _name() async { + var host = ''; try { if (Platform.isIOS) { final i = await DeviceInfoPlugin().iosInfo; - return i.name.isNotEmpty ? i.name : i.utsname.machine; - } - if (Platform.isAndroid) { + host = i.name.isNotEmpty ? i.name : i.utsname.machine; + } else if (Platform.isAndroid) { final a = await DeviceInfoPlugin().androidInfo; - return '${a.manufacturer} ${a.model}'.trim(); + host = a.model; + } else { + host = Platform.localHostname; } - // 桌面:主机名最有意义(MacBook-Pro / DESKTOP-XXXX)。 - return Platform.localHostname; } catch (_) { - return currentPlatform(); + host = ''; } + host = host.trim(); + if (host.length > 8) host = host.substring(0, 8); + final short = _shortPlatform(currentPlatform()); + return host.isEmpty ? short : '$short·$host'; } Future _clientVersion() async { diff --git a/client/lib/state/account_providers.dart b/client/lib/state/account_providers.dart index 224e919..1aea2af 100644 --- a/client/lib/state/account_providers.dart +++ b/client/lib/state/account_providers.dart @@ -95,6 +95,13 @@ class DevicesNotifier extends AsyncNotifier> { ref.invalidateSelf(); await future; } + + /// 重命名设备后刷新列表。 + Future rename(String uuid, String name) async { + await ref.read(accountApiProvider).renameDevice(uuid, name); + ref.invalidateSelf(); + await future; + } } final devicesProvider = diff --git a/client/lib/widgets/account_screens.dart b/client/lib/widgets/account_screens.dart index d1f8b59..ae9ca66 100644 --- a/client/lib/widgets/account_screens.dart +++ b/client/lib/widgets/account_screens.dart @@ -219,6 +219,10 @@ class DevicesScreen extends ConsumerWidget { color: c.surface, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(PangolinRadius.md), side: BorderSide(color: c.border)), itemBuilder: (_) => [ + PopupMenuItem(value: 'rename', child: Row(children: [ + Icon(PangolinIcons.edit, size: 16, color: c.fg2), const SizedBox(width: 10), + Text(t.devRename, style: PangolinText.sm.copyWith(color: c.fg1)), + ])), PopupMenuItem(value: 'logout', child: Row(children: [ Icon(PangolinIcons.logOut, size: 16, color: c.fg2), const SizedBox(width: 10), Text(t.devForceLogout, style: PangolinText.sm.copyWith(color: c.fg1)), @@ -229,6 +233,13 @@ class DevicesScreen extends ConsumerWidget { ])), ], onSelected: (v) async { + if (v == 'rename') { + final newName = await _renameDialog(context, c, d); + if (newName != null && newName.trim().isNotEmpty) { + await ref.read(devicesProvider.notifier).rename(d.uuid, newName.trim()); + } + return; + } final isClear = v == 'clear'; final label = isClear ? t.devClearLogin : t.devForceLogout; final shown = d.name.isNotEmpty ? d.name : d.platformKind.label; @@ -271,6 +282,37 @@ class DevicesScreen extends ConsumerWidget { ); return ok ?? false; } + + // 重命名弹窗:预填当前名,返回新名(取消返回 null)。 + Future _renameDialog(BuildContext context, PangolinScheme c, Device d) { + final ctl = TextEditingController(text: d.name); + return showDialog( + context: context, + builder: (ctx) => AlertDialog( + backgroundColor: c.surface, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(PangolinRadius.xl)), + title: Text(t.devRename, style: PangolinText.body.copyWith(color: c.fg1, fontWeight: FontWeight.w700)), + content: TextField( + controller: ctl, + autofocus: true, + maxLength: 64, + style: PangolinText.sm.copyWith(color: c.fg1), + decoration: InputDecoration( + hintText: t.devRenameHint, + counterText: '', + hintStyle: PangolinText.sm.copyWith(color: c.fg3), + ), + onSubmitted: (v) => Navigator.pop(ctx, v), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), + child: Text(t.devCancel, style: PangolinText.sm.copyWith(color: c.fg2, fontWeight: FontWeight.w600))), + TextButton(onPressed: () => Navigator.pop(ctx, ctl.text), + child: Text(t.devSave, style: PangolinText.sm.copyWith(color: c.accent, fontWeight: FontWeight.w700))), + ], + ), + ); + } } /// ── 兑换 & 购买 ── (兑换码走 POST /v1/redeem,成功后刷新账户) diff --git a/client/lib/widgets/pangolin_icons.dart b/client/lib/widgets/pangolin_icons.dart index f548dd2..6a649e7 100644 --- a/client/lib/widgets/pangolin_icons.dart +++ b/client/lib/widgets/pangolin_icons.dart @@ -58,6 +58,7 @@ class PangolinIcons { static const moreVertical = LucideIcons.moreVertical; static const trash = LucideIcons.trash2; static const alertTriangle= LucideIcons.alertTriangle; + static const edit = LucideIcons.pencil; static IconData? byName(String name) => _byName[name]; diff --git a/client/pubspec.yaml b/client/pubspec.yaml index f33fccd..d32ad8e 100644 --- a/client/pubspec.yaml +++ b/client/pubspec.yaml @@ -1,7 +1,7 @@ name: pangolin_vpn description: 穿山甲 · Pangolin — 极简、稳定、跨平台网络加速客户端。 publish_to: "none" -version: 1.0.12+13 +version: 1.0.13+14 environment: sdk: ^3.5.0 diff --git a/client/test/widget/devices_screen_test.dart b/client/test/widget/devices_screen_test.dart index 6e28e36..1b3b442 100644 --- a/client/test/widget/devices_screen_test.dart +++ b/client/test/widget/devices_screen_test.dart @@ -124,4 +124,18 @@ void main() { expect(recorded.any((r) => r == 'DELETE /v1/me/devices/phone-uuid'), isTrue, reason: '应调清除接口: $recorded'); }); + + testWidgets('重命名 → 输入新名 → 保存 → 调 rename 接口', (tester) async { + await pump(tester); + await tester.tap(find.byType(PopupMenuButton)); + await tester.pumpAndSettle(); + await tester.tap(find.text(t.devRename)); + await tester.pumpAndSettle(); + // 弹窗里输入新名。 + await tester.enterText(find.byType(TextField).last, '我的手机'); + await tester.tap(find.widgetWithText(TextButton, t.devSave)); + await tester.pumpAndSettle(); + expect(recorded.any((r) => r == 'POST /v1/me/devices/phone-uuid/rename'), isTrue, + reason: '应调重命名接口: $recorded'); + }); } diff --git a/client/windows/installer/pangolin.iss b/client/windows/installer/pangolin.iss index b7394d2..f5d66f6 100644 --- a/client/windows/installer/pangolin.iss +++ b/client/windows/installer/pangolin.iss @@ -3,7 +3,7 @@ ; 前置: 先在 client/ 跑 `flutter build windows`(Release),产物在 ; ..\..\build\windows\x64\runner\Release #define MyAppName "穿山甲 Pangolin" -#define MyAppVersion "1.0.12" +#define MyAppVersion "1.0.13" #define MyAppPublisher "Pangolin" #define MyAppExeName "pangolin_vpn.exe" #define BuildDir "..\..\build\windows\x64\runner\Release" diff --git a/server/internal/devices/handler.go b/server/internal/devices/handler.go index 3a47a5f..7f7c0fe 100644 --- a/server/internal/devices/handler.go +++ b/server/internal/devices/handler.go @@ -28,6 +28,7 @@ func (h *Handler) RegisterRoutes(r chi.Router) { r.Get("/devices", h.ListDevices) r.Delete("/devices/{id}", h.DeleteDevice) r.Post("/devices/{id}/logout", h.ForceLogout) + r.Post("/devices/{id}/rename", h.RenameDevice) } type listDevicesResponse struct { @@ -87,3 +88,25 @@ func (h *Handler) ForceLogout(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } + +// RenameDevice handles POST /v1/me/devices/{id}/rename — set a device's name. +func (h *Handler) RenameDevice(w http.ResponseWriter, r *http.Request) { + userID, ok := auth.UserIDFromContext(r.Context()) + if !ok { + apierr.WriteJSON(w, http.StatusUnauthorized, apierr.ErrUnauthorized) + return + } + var req struct { + Name string `json:"name"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<14)).Decode(&req); err != nil { + apierr.WriteJSON(w, http.StatusBadRequest, apierr.ErrBadRequest) + return + } + deviceUUID := chi.URLParam(r, "id") + if apiErr := h.svc.RenameDevice(r.Context(), userID, deviceUUID, req.Name); apiErr != nil { + apierr.WriteJSON(w, StatusForError(apiErr), apiErr) + return + } + w.WriteHeader(http.StatusNoContent) +} diff --git a/server/internal/devices/service.go b/server/internal/devices/service.go index 3dff91b..0f1bf1d 100644 --- a/server/internal/devices/service.go +++ b/server/internal/devices/service.go @@ -312,6 +312,36 @@ func (svc *Service) ForceLogout(ctx context.Context, userID int64, deviceUUID st return nil } +// RenameDevice sets a device's display name (ownership-checked). Empty name → +// 400; name is trimmed + truncated to 64 runes. +// +// - device not found → 404 +// - device owned by another user → 403 +func (svc *Service) RenameDevice(ctx context.Context, userID int64, deviceUUID, rawName string) *apierr.Error { + uuid := strings.TrimSpace(deviceUUID) + name := strings.TrimSpace(rawName) + if uuid == "" || name == "" { + return apierr.ErrBadRequest + } + if r := []rune(name); len(r) > 64 { + name = string(r[:64]) + } + dev, err := svc.store.FindByUUID(ctx, uuid) + if err != nil { + return apierr.ErrInternal + } + if dev == nil { + return apierr.ErrNotFound + } + if dev.UserID != userID { + return apierr.ErrForbidden + } + if err := svc.store.UpdateName(ctx, dev.ID, name); err != nil { + return apierr.ErrInternal + } + return nil +} + // revokeDeviceSessions marks all of a device's sessions revoked and drops their // refresh JTIs from the Redis whitelist. Best-effort. func (svc *Service) revokeDeviceSessions(ctx context.Context, userID, deviceID int64) { diff --git a/server/internal/devices/store.go b/server/internal/devices/store.go index 4867090..4c8a0bd 100644 --- a/server/internal/devices/store.go +++ b/server/internal/devices/store.go @@ -179,6 +179,14 @@ func nullStr(s string) any { return s } +// UpdateName sets a device's display name (non-tx). Used by rename. +func (s *Store) UpdateName(ctx context.Context, deviceID int64, name string) error { + if _, err := s.db.ExecContext(ctx, `UPDATE devices SET name=? WHERE id=?`, name, deviceID); err != nil { + return fmt.Errorf("store.UpdateName: %w", err) + } + return nil +} + // deleteDeviceTx hard-deletes a device row inside tx. func (s *Store) deleteDeviceTx(ctx context.Context, tx *sql.Tx, deviceID int64) error { if _, err := tx.ExecContext(ctx, `DELETE FROM devices WHERE id=?`, deviceID); err != nil { diff --git a/server/internal/store/devices_rename_test.go b/server/internal/store/devices_rename_test.go new file mode 100644 index 0000000..b31435a --- /dev/null +++ b/server/internal/store/devices_rename_test.go @@ -0,0 +1,41 @@ +package store_test + +import ( + "context" + "testing" + + "github.com/wangjia/pangolin/server/internal/devices" +) + +func TestSQLite_RenameDevice(t *testing.T) { + ctx := context.Background() + db := openSQLite(t) + if _, err := db.Exec(`INSERT INTO users (id,uuid,email,pw_hash,dp_uuid,status) VALUES (1,'u1','u1@e','h','dp1','active'),(2,'u2','u2@e','h','dp2','active')`); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO devices (id,uuid,user_id,name,platform) VALUES (10,'devA',1,'Win·old','windows'),(30,'devC',2,'C','ios')`); err != nil { + t.Fatal(err) + } + svc := devices.NewService(devices.NewStore(db), nil) + + if e := svc.RenameDevice(ctx, 1, "devA", "我的台式机"); e != nil { + t.Fatalf("rename: %v", e) + } + var name string + db.QueryRow(`SELECT name FROM devices WHERE id=10`).Scan(&name) + if name != "我的台式机" { + t.Fatalf("name = %q, want 我的台式机", name) + } + // 空名 → 400 + if e := svc.RenameDevice(ctx, 1, "devA", " "); e == nil { + t.Fatal("empty name should fail") + } + // 他人设备 → 403 + if e := svc.RenameDevice(ctx, 1, "devC", "x"); e == nil { + t.Fatal("renaming other user's device should fail") + } + // 不存在 → 404 + if e := svc.RenameDevice(ctx, 1, "nope", "x"); e == nil { + t.Fatal("unknown device should fail") + } +}