Skip to content

Commit 1bbe740

Browse files
CopilotRavelloH
andauthored
ref: 提取公共函数以优化结构 (#33)
* Initial plan * Changes before error encountered Co-authored-by: RavelloH <68409330+RavelloH@users.noreply.github.com> * Fix unused ShotDateTimeParts import and complete refactoring Co-authored-by: RavelloH <68409330+RavelloH@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: RavelloH <68409330+RavelloH@users.noreply.github.com>
1 parent 15a6041 commit 1bbe740

File tree

17 files changed

+181
-192
lines changed

17 files changed

+181
-192
lines changed

apps/web/src/actions/comment.ts

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ import type {
4242
ApiResponse,
4343
ApiResponseData,
4444
} from "@repo/shared-types/api/common";
45-
import crypto from "crypto";
4645
import { headers } from "next/headers";
4746
import type { NextResponse } from "next/server";
4847
import { after } from "next/server";
@@ -58,6 +57,7 @@ import { authVerify } from "@/lib/server/auth-verify";
5857
import { generateCacheKey, getCache, setCache } from "@/lib/server/cache";
5958
import { verifyToken } from "@/lib/server/captcha";
6059
import { getConfig, getConfigs } from "@/lib/server/config-cache";
60+
import { calculateMD5 } from "@/lib/server/crypto";
6161
import { getClientIP } from "@/lib/server/get-client-info";
6262
import { resolveIpLocation } from "@/lib/server/ip-utils";
6363
import {
@@ -93,14 +93,6 @@ type CommentTarget =
9393
updatedAt: Date | null;
9494
};
9595

96-
// 计算 MD5 哈希值的辅助函数
97-
function calculateMD5(text: string): string {
98-
return crypto
99-
.createHash("md5")
100-
.update(text.toLowerCase().trim())
101-
.digest("hex");
102-
}
103-
10496
function toAbsolutePath(pathname: string): string {
10597
return normalizePageSlug(pathname);
10698
}

apps/web/src/actions/message.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,14 @@ import {
2222
SearchUsersRequestSchema,
2323
SendMessageRequestSchema,
2424
} from "@repo/shared-types/api/message";
25-
import crypto from "crypto";
2625
import { cookies, headers } from "next/headers";
2726
import type { NextResponse } from "next/server";
2827

2928
import { checkUserOnlineStatus, publishNoticeToUser } from "@/lib/server/ably";
3029
import { isAblyEnabled } from "@/lib/server/ably-config";
3130
import { authVerify } from "@/lib/server/auth-verify";
3231
import { getConfig } from "@/lib/server/config-cache";
32+
import { calculateMD5 } from "@/lib/server/crypto";
3333
import { sendNotice } from "@/lib/server/notice";
3434
import prisma from "@/lib/server/prisma";
3535
import limitControl from "@/lib/server/rate-limit";
@@ -42,12 +42,6 @@ type ActionResult<T extends ApiResponseData> =
4242
| NextResponse<ApiResponse<T>>
4343
| ApiResponse<T>;
4444

45-
function calculateMD5(text: string): string {
46-
return crypto
47-
.createHash("md5")
48-
.update(text.toLowerCase().trim())
49-
.digest("hex");
50-
}
5145
/**
5246
* 检查消息系统是否启用
5347
*/

apps/web/src/actions/user.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,13 @@ import {
3131
UpdateUserProfileSchema,
3232
UpdateUsersSchema,
3333
} from "@repo/shared-types/api/user";
34-
import crypto from "crypto";
3534
import { updateTag } from "next/cache";
3635
import { cookies, headers } from "next/headers";
3736
import type { NextResponse } from "next/server";
3837

3938
import { logAuditEvent } from "@/lib/server/audit";
4039
import { authVerify } from "@/lib/server/auth-verify";
40+
import { calculateMD5 } from "@/lib/server/crypto";
4141
import { type AccessTokenPayload, jwtTokenVerify } from "@/lib/server/jwt";
4242
import { hashPassword } from "@/lib/server/password";
4343
import prisma from "@/lib/server/prisma";
@@ -53,13 +53,6 @@ type ActionResult<T extends ApiResponseData> =
5353
| NextResponse<ApiResponse<T>>
5454
| ApiResponse<T>;
5555

56-
function calculateMD5(text: string): string {
57-
return crypto
58-
.createHash("md5")
59-
.update(text.toLowerCase().trim())
60-
.digest("hex");
61-
}
62-
6356
/*
6457
getUsersTrends - 获取用户趋势数据
6558
*/

apps/web/src/app/(admin)/admin/cloud/CloudHistoryTable.tsx

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { getCloudHistory } from "@/actions/cloud";
1212
import type { FilterConfig } from "@/components/ui/GridTable";
1313
import GridTable from "@/components/ui/GridTable";
1414
import { useBroadcast } from "@/hooks/use-broadcast";
15+
import { formatDateTimeWithSeconds } from "@/lib/shared/date-format";
1516
import Clickable from "@/ui/Clickable";
1617
import { Dialog } from "@/ui/Dialog";
1718
import type { TableColumn } from "@/ui/Table";
@@ -50,17 +51,6 @@ const TRIGGER_TYPE_LABELS: Record<CloudHistoryItem["triggerType"], string> = {
5051
AUTO: "自动触发",
5152
};
5253

53-
function formatDateTime(value: string): string {
54-
return new Date(value).toLocaleString("zh-CN", {
55-
year: "numeric",
56-
month: "2-digit",
57-
day: "2-digit",
58-
hour: "2-digit",
59-
minute: "2-digit",
60-
second: "2-digit",
61-
});
62-
}
63-
6454
function getDisplayStatus(
6555
record: Pick<CloudHistoryItem, "status" | "receivedAt">,
6656
): CloudDisplayStatus {
@@ -460,7 +450,7 @@ export default function CloudHistoryTable() {
460450
sortable: true,
461451
mono: true,
462452
render: (value: unknown) =>
463-
typeof value === "string" ? formatDateTime(value) : "-",
453+
typeof value === "string" ? formatDateTimeWithSeconds(value) : "-",
464454
},
465455
{
466456
key: "updatedAt",
@@ -470,7 +460,7 @@ export default function CloudHistoryTable() {
470460
sortable: true,
471461
mono: true,
472462
render: (value: unknown) =>
473-
typeof value === "string" ? formatDateTime(value) : "-",
463+
typeof value === "string" ? formatDateTimeWithSeconds(value) : "-",
474464
},
475465
{
476466
key: "detail",
@@ -580,7 +570,7 @@ export default function CloudHistoryTable() {
580570
接收时间
581571
</label>
582572
<p className="text-sm font-mono">
583-
{formatDateTime(selectedRecord.receivedAt)}
573+
{formatDateTimeWithSeconds(selectedRecord.receivedAt)}
584574
</p>
585575
</div>
586576
<div>
@@ -589,7 +579,7 @@ export default function CloudHistoryTable() {
589579
</label>
590580
<p className="text-sm font-mono">
591581
{selectedRecord.requestedAt
592-
? formatDateTime(selectedRecord.requestedAt)
582+
? formatDateTimeWithSeconds(selectedRecord.requestedAt)
593583
: "-"}
594584
</p>
595585
</div>
@@ -598,15 +588,15 @@ export default function CloudHistoryTable() {
598588
创建时间
599589
</label>
600590
<p className="text-sm font-mono">
601-
{formatDateTime(selectedRecord.createdAt)}
591+
{formatDateTimeWithSeconds(selectedRecord.createdAt)}
602592
</p>
603593
</div>
604594
<div>
605595
<label className="text-sm text-muted-foreground">
606596
更新时间
607597
</label>
608598
<p className="text-sm font-mono">
609-
{formatDateTime(selectedRecord.updatedAt)}
599+
{formatDateTimeWithSeconds(selectedRecord.updatedAt)}
610600
</p>
611601
</div>
612602
<div>

apps/web/src/app/(admin)/admin/cloud/CloudReport.tsx

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
import { GridItem } from "@/components/client/layout/RowGrid";
2020
import ErrorPage from "@/components/ui/Error";
2121
import { useBroadcast, useBroadcastSender } from "@/hooks/use-broadcast";
22+
import { formatDateTimeWithSeconds } from "@/lib/shared/date-format";
2223
import { AutoTransition } from "@/ui/AutoTransition";
2324
import { Button } from "@/ui/Button";
2425
import Clickable from "@/ui/Clickable";
@@ -53,17 +54,6 @@ const VERIFY_SOURCE_LABELS: Record<
5354
NONE: "NONE",
5455
};
5556

56-
function formatDateTime(value: string): string {
57-
return new Date(value).toLocaleString("zh-CN", {
58-
year: "numeric",
59-
month: "2-digit",
60-
day: "2-digit",
61-
hour: "2-digit",
62-
minute: "2-digit",
63-
second: "2-digit",
64-
});
65-
}
66-
6757
function formatRate(value: number | null | undefined): string {
6858
if (typeof value !== "number" || !Number.isFinite(value)) return "-";
6959
return `${(value * 100).toFixed(2)}%`;
@@ -162,7 +152,9 @@ function buildSummary(
162152
`云端状态:${remoteStatus};事件总数 ${remote.eventsTotal ?? "-"},成功率 ${formatRate(remote.successRate)}。`,
163153
);
164154
if (remote.registeredAt) {
165-
lines.push(`注册时间:${formatDateTime(remote.registeredAt)}。`);
155+
lines.push(
156+
`注册时间:${formatDateTimeWithSeconds(remote.registeredAt)}。`,
157+
);
166158
}
167159
const localMinuteSlot = utcMinuteToLocalHhMm(remote.minuteOfDay);
168160
if (localMinuteSlot) {
@@ -179,7 +171,7 @@ function buildSummary(
179171
} else {
180172
const latestStatus = getLocalDisplayStatus(latest);
181173
lines.push(
182-
`本地最近投递:${formatDateTime(latest.receivedAt)},状态 ${LOCAL_STATUS_LABELS[latestStatus]},验签来源 ${latest.verifySource ? VERIFY_SOURCE_LABELS[latest.verifySource] : "无"}。`,
174+
`本地最近投递:${formatDateTimeWithSeconds(latest.receivedAt)},状态 ${LOCAL_STATUS_LABELS[latestStatus]},验签来源 ${latest.verifySource ? VERIFY_SOURCE_LABELS[latest.verifySource] : "无"}。`,
183175
);
184176
}
185177
return lines;
@@ -359,7 +351,7 @@ export default function CloudReport() {
359351
</div>
360352
<div className="inline-flex items-center gap-2">
361353
最近刷新于:{" "}
362-
{formatDateTime(
354+
{formatDateTimeWithSeconds(
363355
latestRecord?.receivedAt ||
364356
config.updatedAt ||
365357
new Date().toISOString(),

apps/web/src/app/(admin)/admin/friends/FriendsTable.tsx

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import type { ActionButton, FilterConfig } from "@/components/ui/GridTable";
2222
import GridTable from "@/components/ui/GridTable";
2323
import Link from "@/components/ui/Link";
2424
import { useBroadcast, useBroadcastSender } from "@/hooks/use-broadcast";
25+
import { formatDateTimeLocale } from "@/lib/shared/date-format";
2526
import { AlertDialog } from "@/ui/AlertDialog";
2627
import type { TableColumn } from "@/ui/Table";
2728
import { useToast } from "@/ui/Toast";
@@ -69,11 +70,6 @@ const statusClassName: Record<FriendLinkStatus, string> = {
6970
BLOCKED: "text-error",
7071
};
7172

72-
function formatDateTime(value: string | null): string {
73-
if (!value) return "-";
74-
return new Date(value).toLocaleString("zh-CN");
75-
}
76-
7773
function getRateClass(rate: number): string {
7874
if (rate >= 90) return "text-foreground";
7975
if (rate >= 50) return "text-warning";
@@ -519,7 +515,7 @@ export default function FriendsTable() {
519515
sortable: true,
520516
mono: true,
521517
render: (value) =>
522-
formatDateTime(typeof value === "string" ? value : null),
518+
formatDateTimeLocale(typeof value === "string" ? value : null),
523519
},
524520
{
525521
key: "createdAt",
@@ -529,7 +525,7 @@ export default function FriendsTable() {
529525
sortable: true,
530526
mono: true,
531527
render: (value) =>
532-
formatDateTime(typeof value === "string" ? value : null),
528+
formatDateTimeLocale(typeof value === "string" ? value : null),
533529
},
534530
];
535531

apps/web/src/app/(build-in)/friends/new/FriendLinkApplyClient.tsx

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import AreaChart, {
2626
import { CaptchaButton } from "@/components/ui/CaptchaButton";
2727
import { useNavigateWithTransition } from "@/components/ui/Link";
2828
import { useBroadcast, useBroadcastSender } from "@/hooks/use-broadcast";
29+
import { formatDateTimeLocale } from "@/lib/shared/date-format";
2930
import { AlertDialog } from "@/ui/AlertDialog";
3031
import { AutoResizer } from "@/ui/AutoResizer";
3132
import { AutoTransition } from "@/ui/AutoTransition";
@@ -116,11 +117,6 @@ const responseTimeSeries: SeriesConfig[] = [
116117
},
117118
];
118119

119-
function formatDateTime(value: string | null): string {
120-
if (!value) return "-";
121-
return new Date(value).toLocaleString("zh-CN");
122-
}
123-
124120
function buildFormFromRecord(
125121
record: FriendLinkListItem | null,
126122
): FriendLinkApplyForm {
@@ -475,7 +471,7 @@ export default function FriendLinkApplyClient({
475471
width: 180,
476472
mono: true,
477473
render: (value) =>
478-
formatDateTime(typeof value === "string" ? value : null),
474+
formatDateTimeLocale(typeof value === "string" ? value : null),
479475
},
480476
{
481477
key: "result",
@@ -697,15 +693,15 @@ export default function FriendLinkApplyClient({
697693
创建时间
698694
</div>
699695
<div className="mt-1 text-sm font-mono">
700-
{formatDateTime(ownFriendLink.createdAt)}
696+
{formatDateTimeLocale(ownFriendLink.createdAt)}
701697
</div>
702698
</div>
703699
<div>
704700
<div className="text-sm text-muted-foreground">
705701
最近更新时间
706702
</div>
707703
<div className="mt-1 text-sm font-mono">
708-
{formatDateTime(ownFriendLink.updatedAt)}
704+
{formatDateTimeLocale(ownFriendLink.updatedAt)}
709705
</div>
710706
</div>
711707
<div>
@@ -739,7 +735,7 @@ export default function FriendLinkApplyClient({
739735
最近检查
740736
</div>
741737
<div className="mt-1 text-sm font-mono">
742-
{formatDateTime(ownFriendLink.lastCheckedAt)}
738+
{formatDateTimeLocale(ownFriendLink.lastCheckedAt)}
743739
</div>
744740
</div>
745741
<div>

apps/web/src/app/(build-in)/gallery/@modal/(.)photo/[slug]/PhotoModalClient.tsx

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
formatMeteringMode,
2727
formatSceneCaptureType,
2828
formatSensingMethod,
29+
formatShotDateTime,
2930
formatWhiteBalance,
3031
type ParsedExifData,
3132
parseExifBuffer,
@@ -53,35 +54,6 @@ function formatResolution(
5354
return `${xRes} × ${yRes} ${unitStr}`;
5455
}
5556

56-
// 格式化拍摄时间(返回分离的部分以便分别设置样式)
57-
interface ShotDateTimeParts {
58-
dateStr: string;
59-
offsetTime?: string;
60-
subSecTime?: string;
61-
}
62-
63-
function formatShotDateTime(
64-
dateTime: Date | undefined,
65-
offsetTime: string | undefined,
66-
subSecTime: string | undefined,
67-
): ShotDateTimeParts | null {
68-
if (!dateTime) return null;
69-
const date = new Date(dateTime);
70-
const dateStr = date.toLocaleString("zh-CN", {
71-
year: "numeric",
72-
month: "2-digit",
73-
day: "2-digit",
74-
hour: "2-digit",
75-
minute: "2-digit",
76-
second: "2-digit",
77-
});
78-
return {
79-
dateStr,
80-
offsetTime: offsetTime || undefined,
81-
subSecTime: subSecTime || undefined,
82-
};
83-
}
84-
8557
// 格式化 GPS 方向
8658
function formatGpsDirection(direction: number): string {
8759
return `${direction.toFixed(1)}° (罗盘方位)`;

0 commit comments

Comments
 (0)