diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..fa6123e
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,12 @@
+# 复制为 .env;此文件不能填写真实凭据后提交。
+DB_URL='jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf8&connectionTimeZone=UTC'
+DB_USERNAME=community_app
+DB_PASSWORD='replace-with-your-database-password'
+GITEA_BASE_URL=http://localhost:3000
+GITEA_ORGANIZATION=community
+GITEA_TOKEN='replace-with-your-gitea-token'
+# 默认 test,部署生产环境时改为 prod;连接信息也应对应生产环境。
+SPRING_PROFILES_ACTIVE=test
+# 不设置 LOG_PATH 时,日志按环境写入 logs/test 或 logs/prod。
+# LOG_PATH=/data/community/logs
+PORT=8993
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9fa77e2
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+.idea/
+**/target/
+.env
+.DS_Store
+logs/
diff --git a/README.md b/README.md
index ec9e76b..fafb39f 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,78 @@
-# community
+# Community
+
+Spring Boot 社区后端,工程分层参考 cadworld。使用 Java 21、Spring Boot 3.5.7、MyBatis-Plus 3.5.11、MySQL 和 Gitea API v1。业务库名为 community,只有 sys_user、project、project_comment、project_like 四张表。
+
+平台管理用户、项目归属、类型、发布、评论、点赞和 Fork 来源;Gitea 管理文件、目录、Commit 与历史。仓库统一存放在配置的 Gitea 组织下,为私有仓库。
+
+内置项目类型为 GENERAL(通用)、HUMANOID(人形)、QUADRUPED(四足)、WHEELED(轮式)。前端通过 `/api/project-types` 获取类型列表,用于项目创建、修改和列表筛选。
+
+## 功能与边界
+
+支持邮箱加图片验证码登录、我的项目列表、在线文本编辑、新建文件和目录、上传及多文件提交、手动发布和撤回、已发布版本浏览、快照 Fork、平铺评论和点赞。工作区是用户项目列表,没有 workspace 表。没有 repository_operation 表、草稿保存、AI、类型表、标签、收藏、成员协作或管理后台。
+
+**当前登录不验证邮箱归属,知道别人的邮箱也可能登录其账号。** 验证码和登录会话使用本机缓存,单实例部署,重启后重新登录。所有仓库写入统一经过平台后端。
+
+## 启动
+
+1. 安装 Java 21、Maven 3.9+,准备 MySQL 8 和现有 Gitea。
+2. 手动执行 [四表建表 SQL](docs/database.md),应用不会自动建表或修改数据库。
+3. 在 Gitea 创建私有组织,将技术账号设为组织所有者,生成具有 write:repository、write:organization、read:user 权限的 Token。
+4. 将 .env.example 复制为 .env,填写数据库连接与 Gitea 地址、组织、Token;默认使用 test 环境,.env 被 Git 忽略,不提交真实凭据。
+5. 执行:
+
+```bash
+bash scripts/run-local.sh
+```
+
+当前机器已配置 Gitea 26.4.0,并建立私有组织 community。本机 .env 已保存 Gitea Token,权限为 0600;没有保存管理员密码。保留这些 Gitea 配置,再补充 DB_URL、DB_USERNAME、DB_PASSWORD 即可,不要用示例覆盖已有 Token。
+
+直接部署时通过环境变量配置,运行打包后的 community-api/target/community-api-0.0.1-SNAPSHOT.jar。默认端口 8993,SERVER_PORT 或 PORT 可覆盖(SERVER_PORT 优先)。本机脚本会加载 .env,直接运行 jar 不会自动加载该文件。
+
+接口文档:[前端接口对接文档](docs/api.md),包含全部接口、字段结构、请求响应示例、页面调用顺序和错误处理。启动后访问 /swagger-ui.html;机器可读 OpenAPI 为 /v3/api-docs。
+
+## 环境与日志
+
+配置与日志方式参考 cadworld:application.yml 保存公共配置,application-test.yml 和 application-prod.yml 分别保存环境相关的数据库、Gitea 和日志配置。不指定环境时默认 test,通过 SPRING_PROFILES_ACTIVE 或启动参数切换。
+
+prod 启动时检查数据库连接、用户名、密码、Gitea 地址和 Token 是否已配置且非空;缺失时停止启动,错误信息只包含配置项名称。
+
+| 配置 | test | prod |
+| --- | --- | --- |
+| 数据库 | 默认本机 community,可用 DB_* 覆盖 | 必须配置 DB_URL、DB_USERNAME、DB_PASSWORD |
+| Gitea | 默认本机地址,使用 GITEA_* 覆盖 | 必须配置 GITEA_BASE_URL、GITEA_TOKEN;组织默认 community |
+| 连接池 | 最少 1、最多 10 个连接 | 最少 1、最多 20 个连接 |
+| 项目日志级别 | DEBUG | INFO |
+| 日志目录 | logs/test | logs/prod |
+
+生产部署示例(先在部署环境配置以上连接变量):
+
+```bash
+SPRING_PROFILES_ACTIVE=prod java -Djava.awt.headless=true -jar community-api/target/community-api-0.0.1-SNAPSHOT.jar
+```
+
+本机脚本支持传递启动参数,例如 `bash scripts/run-local.sh --spring.profiles.active=prod`,此时加载 .env 中的连接信息并使用 prod 配置。测试和生产数据库、Gitea 组织需要各自隔离时,分别设置对应的 DB_*、GITEA_* 变量。
+
+公共模块的 logback-spring.xml 同时输出控制台、community.log 和 community-error.log,日志时间使用 Asia/Shanghai,包含线程、requestId 和业务编码。应用日志按天或每 100MB 归档,保留 30 天、总归档上限 10GB;错误日志按天或每 50MB 归档,保留 60 天、总归档上限 5GB。可用 LOG_PATH 覆盖日志目录。SQL Mapper 和 Spring Web 保持 INFO,不记录凭据、邮箱或代码内容。
+
+## 验证
+
+```bash
+mvn clean verify
+```
+
+普通测试固定使用 test 配置,覆盖连接为临时 H2 MySQL 模式及模拟 Gitea,验证登录、权限、提交冲突、发布快照、Fork、评论、点赞和超时处理,不访问真实数据库或仓库。
+
+真实 Gitea 联调:
+
+```bash
+python3 scripts/test-gitea.py
+```
+
+该测试使用临时 H2 数据库,在配置的组织创建临时项目仓库,验证私有仓库、多文件提交、中文路径、二进制上传、固定发布版本及快照 Fork,结束后仅删除本次测试创建的仓库。Gitea 26.4.0 内置的 1.26.4 支持批量文件变更;以服务器 /swagger.v1.json 为对接依据。
+
+## 运行约定
+
+项目名称、描述、类型修改直接更新展示;工作区代码提交后,社区仍读取已发布 SHA,需要手动更新。Fork 复制已发布文件快照,不继承上游提交历史,也不自动同步。项目删除采用逻辑删除,保留仓库和已有 Fork。
+
+创建或 Fork 前先写入 CREATING 项目,成功后标记 READY。结果不明或数据库回写失败需要人工核对;不提供后台自动恢复、无条件自动重试或跨重启完整幂等。具体恢复方式见接口文档。
diff --git a/community-api/pom.xml b/community-api/pom.xml
new file mode 100644
index 0000000..6f96f6f
--- /dev/null
+++ b/community-api/pom.xml
@@ -0,0 +1,39 @@
+
+
+ 4.0.0
+
+ com.linkerbot
+ community
+ 0.0.1-SNAPSHOT
+
+ community-api
+
+
+ com.linkerbot
+ community-security
+ ${project.version}
+
+
+ org.springdoc
+ springdoc-openapi-starter-webmvc-ui
+
+
+ com.mysql
+ mysql-connector-j
+ runtime
+
+
+ com.h2database
+ h2
+ test
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
diff --git a/community-api/src/main/java/com/linkerbot/community/api/AuthController.java b/community-api/src/main/java/com/linkerbot/community/api/AuthController.java
new file mode 100644
index 0000000..4dcb960
--- /dev/null
+++ b/community-api/src/main/java/com/linkerbot/community/api/AuthController.java
@@ -0,0 +1,62 @@
+package com.linkerbot.community.api;
+
+import com.linkerbot.community.bean.Contracts.*;
+import com.linkerbot.community.bean.entity.User;
+import com.linkerbot.community.common.ApiResponse;
+import com.linkerbot.community.security.*;
+import com.linkerbot.community.service.UserService;
+import com.linkerbot.community.service.config.CommunityProperties;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.security.SecurityRequirements;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import jakarta.validation.Valid;
+
+import lombok.RequiredArgsConstructor;
+
+import org.springframework.web.bind.annotation.*;
+
+@RestController
+@RequiredArgsConstructor
+@Tag(name = "登录与用户")
+public class AuthController {
+ private final CaptchaService captcha;
+ private final TokenService tokens;
+ private final UserService users;
+ private final CommunityProperties config;
+
+ @GetMapping("/api/auth/captcha")
+ @Operation(summary = "获取一次性图片验证码")
+ @SecurityRequirements
+ public ApiResponse captcha() {
+ return ApiResponse.success(captcha.issue());
+ }
+
+ @PostMapping("/api/auth/login")
+ @Operation(summary = "邮箱和图片验证码登录,首次自动创建用户")
+ @SecurityRequirements
+ public ApiResponse login(@Valid @RequestBody LoginRequest input) {
+ captcha.verify(input.captchaCode(), input.captchaAnswer());
+ User user = users.login(input.email());
+ return ApiResponse.success(
+ new LoginView(
+ tokens.issue(user.getId()),
+ "Bearer",
+ config.getTokenTtl().toSeconds(),
+ users.view(user)));
+ }
+
+ @PostMapping("/api/auth/logout")
+ @Operation(summary = "退出登录")
+ public ApiResponse logout(@RequestHeader("Authorization") String authorization) {
+ tokens.revoke(authorization.startsWith("Bearer ") ? authorization.substring(7) : null);
+ return ApiResponse.success(null);
+ }
+
+ @GetMapping("/api/users/me")
+ @Operation(summary = "当前用户")
+ public ApiResponse me() {
+ return ApiResponse.success(users.view(users.require(CurrentUser.required())));
+ }
+}
diff --git a/community-api/src/main/java/com/linkerbot/community/api/CommunityApplication.java b/community-api/src/main/java/com/linkerbot/community/api/CommunityApplication.java
new file mode 100644
index 0000000..afb37ca
--- /dev/null
+++ b/community-api/src/main/java/com/linkerbot/community/api/CommunityApplication.java
@@ -0,0 +1,16 @@
+package com.linkerbot.community.api;
+
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
+
+@MapperScan("com.linkerbot.community.service.mapper")
+@SpringBootApplication(
+ scanBasePackages = "com.linkerbot.community",
+ exclude = UserDetailsServiceAutoConfiguration.class)
+public class CommunityApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(CommunityApplication.class, args);
+ }
+}
diff --git a/community-api/src/main/java/com/linkerbot/community/api/CommunityController.java b/community-api/src/main/java/com/linkerbot/community/api/CommunityController.java
new file mode 100644
index 0000000..e54f027
--- /dev/null
+++ b/community-api/src/main/java/com/linkerbot/community/api/CommunityController.java
@@ -0,0 +1,131 @@
+package com.linkerbot.community.api;
+
+import com.linkerbot.community.bean.Contracts.*;
+import com.linkerbot.community.common.*;
+import com.linkerbot.community.security.CurrentUser;
+import com.linkerbot.community.service.*;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.security.SecurityRequirements;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import jakarta.validation.Valid;
+
+import lombok.RequiredArgsConstructor;
+
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@Tag(name = "社区")
+public class CommunityController {
+ private final ProjectService projects;
+ private final FileService files;
+ private final InteractionService interactions;
+
+ @GetMapping("/api/project-types")
+ @Operation(summary = "配置中的项目类型")
+ @SecurityRequirements
+ public ApiResponse> types() {
+ return ApiResponse.success(projects.types());
+ }
+
+ @GetMapping("/api/community/projects")
+ @Operation(summary = "已发布项目列表,支持类型和关键词筛选")
+ @SecurityRequirements
+ public ApiResponse> list(
+ @RequestParam(defaultValue = "1") long page,
+ @RequestParam(defaultValue = "20") long size,
+ @RequestParam(required = false) String type,
+ @RequestParam(required = false) String keyword) {
+ return ApiResponse.success(
+ projects.list(null, type, keyword, page, size, CurrentUser.optional()));
+ }
+
+ @GetMapping("/api/community/projects/{projectCode}")
+ @Operation(summary = "社区项目详情")
+ @SecurityRequirements
+ public ApiResponse detail(@PathVariable String projectCode) {
+ return ApiResponse.success(
+ projects.view(projects.published(projectCode), CurrentUser.optional()));
+ }
+
+ @GetMapping("/api/community/projects/{projectCode}/tree")
+ @Operation(summary = "已发布版本的目录")
+ @SecurityRequirements
+ public ApiResponse tree(
+ @PathVariable String projectCode,
+ @RequestParam(defaultValue = "") String path,
+ @RequestParam(required = false) String commitSha) {
+ rejectRef(commitSha);
+ return ApiResponse.success(files.communityTree(projectCode, path));
+ }
+
+ @GetMapping("/api/community/projects/{projectCode}/files")
+ @Operation(summary = "已发布版本文件,download=true 时下载")
+ @SecurityRequirements
+ public ResponseEntity> file(
+ @PathVariable String projectCode,
+ @RequestParam String path,
+ @RequestParam(defaultValue = "false") boolean download,
+ @RequestParam(required = false) String commitSha) {
+ rejectRef(commitSha);
+ return download
+ ? WorkspaceController.download(files.communityFile(projectCode, path))
+ : ResponseEntity.ok(
+ ApiResponse.success(files.communityFileView(projectCode, path)));
+ }
+
+ private void rejectRef(String sha) {
+ if (sha != null) throw BusinessException.badRequest("社区文件仅允许读取当前已发布版本");
+ }
+
+ @PostMapping("/api/community/projects/{projectCode}/forks")
+ @Operation(summary = "复制已发布文件到我的工作区")
+ public ApiResponse fork(
+ @PathVariable String projectCode, @Valid @RequestBody ForkInput input) {
+ return ApiResponse.success(projects.fork(CurrentUser.required(), projectCode, input));
+ }
+
+ @GetMapping("/api/community/projects/{projectCode}/comments")
+ @Operation(summary = "评论列表")
+ @SecurityRequirements
+ public ApiResponse> comments(
+ @PathVariable String projectCode,
+ @RequestParam(defaultValue = "1") long page,
+ @RequestParam(defaultValue = "20") long size) {
+ return ApiResponse.success(interactions.list(projectCode, page, size));
+ }
+
+ @PostMapping("/api/community/projects/{projectCode}/comments")
+ @Operation(summary = "新增纯文本评论")
+ public ApiResponse comment(
+ @PathVariable String projectCode, @Valid @RequestBody CommentInput input) {
+ return ApiResponse.success(
+ interactions.comment(CurrentUser.required(), projectCode, input));
+ }
+
+ @DeleteMapping("/api/comments/{commentCode}")
+ @Operation(summary = "删除自己的评论")
+ public ApiResponse deleteComment(@PathVariable String commentCode) {
+ interactions.deleteComment(CurrentUser.required(), commentCode);
+ return ApiResponse.success(null);
+ }
+
+ @PutMapping("/api/community/projects/{projectCode}/like")
+ @Operation(summary = "幂等点赞")
+ public ApiResponse like(@PathVariable String projectCode) {
+ interactions.like(CurrentUser.required(), projectCode);
+ return ApiResponse.success(null);
+ }
+
+ @DeleteMapping("/api/community/projects/{projectCode}/like")
+ @Operation(summary = "幂等取消点赞")
+ public ApiResponse unlike(@PathVariable String projectCode) {
+ interactions.unlike(CurrentUser.required(), projectCode);
+ return ApiResponse.success(null);
+ }
+}
diff --git a/community-api/src/main/java/com/linkerbot/community/api/OpenApiConfiguration.java b/community-api/src/main/java/com/linkerbot/community/api/OpenApiConfiguration.java
new file mode 100644
index 0000000..283f962
--- /dev/null
+++ b/community-api/src/main/java/com/linkerbot/community/api/OpenApiConfiguration.java
@@ -0,0 +1,30 @@
+package com.linkerbot.community.api;
+
+import io.swagger.v3.oas.models.*;
+import io.swagger.v3.oas.models.info.Info;
+import io.swagger.v3.oas.models.security.*;
+
+import org.springframework.context.annotation.*;
+
+@Configuration
+public class OpenApiConfiguration {
+ @Bean
+ public OpenAPI openAPI() {
+ return new OpenAPI()
+ .info(
+ new Info()
+ .title("Community 首期接口")
+ .version("v1")
+ .description(
+ "四表社区后端。登录仅邮箱和图片验证码,无法验证邮箱归属。Gitea"
+ + " 仓库统一存放在组织下。文件下载返回二进制,其余响应使用统一包装。"))
+ .components(
+ new Components()
+ .addSecuritySchemes(
+ "bearer",
+ new SecurityScheme()
+ .type(SecurityScheme.Type.HTTP)
+ .scheme("bearer")))
+ .addSecurityItem(new SecurityRequirement().addList("bearer"));
+ }
+}
diff --git a/community-api/src/main/java/com/linkerbot/community/api/ProductionConfiguration.java b/community-api/src/main/java/com/linkerbot/community/api/ProductionConfiguration.java
new file mode 100644
index 0000000..ea3d5e9
--- /dev/null
+++ b/community-api/src/main/java/com/linkerbot/community/api/ProductionConfiguration.java
@@ -0,0 +1,32 @@
+package com.linkerbot.community.api;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.env.Environment;
+
+import java.util.List;
+
+@Configuration(proxyBeanMethods = false)
+@Profile("prod")
+public class ProductionConfiguration {
+ public ProductionConfiguration(Environment environment) {
+ for (String property :
+ List.of(
+ "spring.datasource.url",
+ "spring.datasource.username",
+ "spring.datasource.password",
+ "community.gitea.base-url",
+ "community.gitea.token")) {
+ String value;
+ try {
+ value = environment.getRequiredProperty(property);
+ } catch (IllegalArgumentException | IllegalStateException error) {
+ // 仅提示配置项名称,避免异常链携带配置值。
+ throw new IllegalStateException("生产环境必须配置 " + property);
+ }
+ if (value.isBlank()) {
+ throw new IllegalStateException("生产环境必须配置 " + property);
+ }
+ }
+ }
+}
diff --git a/community-api/src/main/java/com/linkerbot/community/api/WorkspaceController.java b/community-api/src/main/java/com/linkerbot/community/api/WorkspaceController.java
new file mode 100644
index 0000000..132fa5e
--- /dev/null
+++ b/community-api/src/main/java/com/linkerbot/community/api/WorkspaceController.java
@@ -0,0 +1,158 @@
+package com.linkerbot.community.api;
+
+import com.linkerbot.community.bean.Contracts.*;
+import com.linkerbot.community.common.*;
+import com.linkerbot.community.security.CurrentUser;
+import com.linkerbot.community.service.*;
+import com.linkerbot.community.service.gitea.GiteaClient;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import jakarta.validation.Valid;
+
+import lombok.RequiredArgsConstructor;
+
+import org.springframework.http.*;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/api/workspace/projects")
+@Tag(name = "我的工作区")
+public class WorkspaceController {
+ private final ProjectService projects;
+ private final FileService files;
+
+ @GetMapping
+ @Operation(summary = "我的项目列表")
+ public ApiResponse> list(
+ @RequestParam(defaultValue = "1") long page,
+ @RequestParam(defaultValue = "20") long size,
+ @RequestParam(required = false) String type,
+ @RequestParam(required = false) String keyword) {
+ long user = CurrentUser.required();
+ return ApiResponse.success(projects.list(user, type, keyword, page, size, user));
+ }
+
+ @PostMapping
+ @Operation(summary = "创建项目和组织中的私有仓库")
+ public ApiResponse create(@Valid @RequestBody ProjectInput input) {
+ return ApiResponse.success(projects.create(CurrentUser.required(), input));
+ }
+
+ @GetMapping("/{projectCode}")
+ @Operation(summary = "我的项目详情")
+ public ApiResponse detail(@PathVariable String projectCode) {
+ long user = CurrentUser.required();
+ return ApiResponse.success(projects.view(projects.owner(user, projectCode), user));
+ }
+
+ @PatchMapping("/{projectCode}")
+ @Operation(summary = "修改名称、描述和类型")
+ public ApiResponse update(
+ @PathVariable String projectCode, @Valid @RequestBody ProjectInput input) {
+ return ApiResponse.success(projects.update(CurrentUser.required(), projectCode, input));
+ }
+
+ @DeleteMapping("/{projectCode}")
+ @Operation(summary = "逻辑删除项目并撤回社区")
+ public ApiResponse delete(@PathVariable String projectCode) {
+ projects.delete(CurrentUser.required(), projectCode);
+ return ApiResponse.success(null);
+ }
+
+ @GetMapping("/{projectCode}/tree")
+ @Operation(summary = "读取目录,可指定本项目 Commit")
+ public ApiResponse tree(
+ @PathVariable String projectCode,
+ @RequestParam(defaultValue = "") String path,
+ @RequestParam(required = false) String commitSha) {
+ return ApiResponse.success(
+ files.ownerTree(CurrentUser.required(), projectCode, path, commitSha));
+ }
+
+ @GetMapping("/{projectCode}/files")
+ @Operation(summary = "读取文件,download=true 时下载")
+ public ResponseEntity> file(
+ @PathVariable String projectCode,
+ @RequestParam String path,
+ @RequestParam(required = false) String commitSha,
+ @RequestParam(defaultValue = "false") boolean download) {
+ long user = CurrentUser.required();
+ if (!download)
+ return ResponseEntity.ok(
+ ApiResponse.success(files.ownerFileView(user, projectCode, path, commitSha)));
+ return download(files.ownerFile(user, projectCode, path, commitSha));
+ }
+
+ public static ResponseEntity download(GiteaClient.StoredFile file) {
+ String name = file.path().substring(file.path().lastIndexOf('/') + 1);
+ return ResponseEntity.ok()
+ .contentType(MediaType.APPLICATION_OCTET_STREAM)
+ .header(
+ HttpHeaders.CONTENT_DISPOSITION,
+ ContentDisposition.attachment()
+ .filename(name, StandardCharsets.UTF_8)
+ .build()
+ .toString())
+ .body(file.bytes());
+ }
+
+ @PostMapping("/{projectCode}/commits")
+ @Operation(summary = "多文件变更提交为一个 Commit")
+ public ApiResponse commit(
+ @PathVariable String projectCode, @Valid @RequestBody CommitInput input) {
+ return ApiResponse.success(files.commit(CurrentUser.required(), projectCode, input));
+ }
+
+ @GetMapping("/{projectCode}/commits")
+ @Operation(summary = "main 提交历史")
+ public ApiResponse> history(
+ @PathVariable String projectCode,
+ @RequestParam(defaultValue = "1") long page,
+ @RequestParam(defaultValue = "20") long size) {
+ return ApiResponse.success(files.history(CurrentUser.required(), projectCode, page, size));
+ }
+
+ @PostMapping(
+ value = "/{projectCode}/uploads/commit",
+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ @Operation(summary = "上传或替换文件并一次提交")
+ public ApiResponse upload(
+ @PathVariable String projectCode,
+ @RequestParam String expectedCommitSha,
+ @RequestParam String message,
+ @RequestParam(defaultValue = "") String directory,
+ @RequestParam("files") List uploaded,
+ @RequestParam(required = false) List paths) {
+ return ApiResponse.success(
+ files.upload(
+ CurrentUser.required(),
+ projectCode,
+ expectedCommitSha,
+ message,
+ directory,
+ uploaded,
+ paths));
+ }
+
+ @PutMapping("/{projectCode}/publication")
+ @Operation(summary = "发布或手动更新社区文件版本")
+ public ApiResponse publish(
+ @PathVariable String projectCode, @Valid @RequestBody PublicationInput input) {
+ return ApiResponse.success(
+ projects.publish(CurrentUser.required(), projectCode, input.commitSha()));
+ }
+
+ @DeleteMapping("/{projectCode}/publication")
+ @Operation(summary = "撤回社区")
+ public ApiResponse withdraw(@PathVariable String projectCode) {
+ projects.withdraw(CurrentUser.required(), projectCode);
+ return ApiResponse.success(null);
+ }
+}
diff --git a/community-api/src/main/resources/application-prod.yml b/community-api/src/main/resources/application-prod.yml
new file mode 100644
index 0000000..e75b243
--- /dev/null
+++ b/community-api/src/main/resources/application-prod.yml
@@ -0,0 +1,23 @@
+spring:
+ datasource:
+ url: ${DB_URL}
+ username: ${DB_USERNAME}
+ password: ${DB_PASSWORD}
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ hikari:
+ pool-name: CommunityHikariCP
+ minimum-idle: 1
+ maximum-pool-size: 20
+ connection-timeout: 5000
+
+community:
+ gitea:
+ base-url: ${GITEA_BASE_URL}
+ owner: ${GITEA_ORGANIZATION:community}
+ token: ${GITEA_TOKEN}
+
+logging:
+ file:
+ path: ${LOG_PATH:logs/prod}
+ level:
+ com.linkerbot.community: INFO
diff --git a/community-api/src/main/resources/application-test.yml b/community-api/src/main/resources/application-test.yml
new file mode 100644
index 0000000..d5d27a9
--- /dev/null
+++ b/community-api/src/main/resources/application-test.yml
@@ -0,0 +1,23 @@
+spring:
+ datasource:
+ url: ${DB_URL:jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf8&connectionTimeZone=UTC}
+ username: ${DB_USERNAME:root}
+ password: ${DB_PASSWORD:}
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ hikari:
+ pool-name: CommunityHikariCP
+ minimum-idle: 1
+ maximum-pool-size: 10
+ connection-timeout: 5000
+
+community:
+ gitea:
+ base-url: ${GITEA_BASE_URL:http://localhost:3000}
+ owner: ${GITEA_ORGANIZATION:community}
+ token: ${GITEA_TOKEN:}
+
+logging:
+ file:
+ path: ${LOG_PATH:logs/test}
+ level:
+ com.linkerbot.community: DEBUG
diff --git a/community-api/src/main/resources/application.yml b/community-api/src/main/resources/application.yml
new file mode 100644
index 0000000..7433b1b
--- /dev/null
+++ b/community-api/src/main/resources/application.yml
@@ -0,0 +1,45 @@
+server:
+ port: ${SERVER_PORT:${PORT:8993}}
+spring:
+ application:
+ name: community
+ profiles:
+ default: test
+ sql:
+ init:
+ mode: never
+ servlet:
+ multipart:
+ max-file-size: 10MB
+ max-request-size: 52MB
+ jackson:
+ time-zone: UTC
+ main:
+ banner-mode: off
+mybatis-plus:
+ configuration:
+ map-underscore-to-camel-case: true
+community:
+ types:
+ GENERAL: 通用
+ HUMANOID: 人形
+ QUADRUPED: 四足
+ WHEELED: 轮式
+ captcha-ttl: 2m
+ token-ttl: 24h
+ max-text-bytes: 1048576
+ max-file-bytes: 10485760
+ max-request-bytes: 52428800
+ gitea:
+ connect-timeout: 5s
+ request-timeout: 30s
+springdoc:
+ swagger-ui:
+ path: /swagger-ui.html
+logging:
+ level:
+ root: INFO
+ org.springframework: INFO
+ # 测试环境开启项目 DEBUG 时,不输出 SQL 参数或完整请求内容。
+ com.linkerbot.community.service.mapper: INFO
+ org.springframework.web: INFO
diff --git a/community-api/src/test/java/com/linkerbot/community/api/FakeGiteaClient.java b/community-api/src/test/java/com/linkerbot/community/api/FakeGiteaClient.java
new file mode 100644
index 0000000..acb4dd0
--- /dev/null
+++ b/community-api/src/test/java/com/linkerbot/community/api/FakeGiteaClient.java
@@ -0,0 +1,149 @@
+package com.linkerbot.community.api;
+
+import com.linkerbot.community.bean.Contracts.*;
+import com.linkerbot.community.common.PageResponse;
+import com.linkerbot.community.service.gitea.*;
+
+import java.security.MessageDigest;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicLong;
+
+final class FakeGiteaClient implements GiteaClient {
+ private static final class RepoData {
+ Repository repository;
+ String head;
+ Map> snapshots = new HashMap<>();
+ List history = new ArrayList<>();
+ }
+
+ private final Map repositories = new HashMap<>();
+ private final AtomicLong sequence = new AtomicLong();
+ boolean timeoutNextCommit;
+ boolean timeoutNextCreate;
+ boolean failNextCreate;
+
+ void reset() {
+ repositories.clear();
+ timeoutNextCommit = false;
+ timeoutNextCreate = false;
+ failNextCreate = false;
+ }
+
+ private String sha() {
+ return String.format("%040x", sequence.incrementAndGet());
+ }
+
+ private String blob(byte[] data) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(data));
+ } catch (Exception error) {
+ throw new IllegalStateException(error);
+ }
+ }
+
+ private RepoData repo(Repository repository) {
+ return repositories.get(repository.id());
+ }
+
+ @Override
+ public synchronized Repository createRepository(String name, boolean initialize) {
+ if (failNextCreate) {
+ failNextCreate = false;
+ throw new GiteaFailure(502, "GITEA_ERROR", "服务拒绝请求", false);
+ }
+ RepoData data = new RepoData();
+ data.repository = new Repository(sequence.incrementAndGet(), "community", name);
+ repositories.put(data.repository.id(), data);
+ if (initialize)
+ commit(
+ data.repository,
+ List.of(new Change("create", "README.md", null, "initial".getBytes())),
+ "Initial commit",
+ "system",
+ "system");
+ if (timeoutNextCreate) {
+ timeoutNextCreate = false;
+ throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "创建结果未知", true);
+ }
+ return data.repository;
+ }
+
+ @Override
+ public synchronized String head(Repository repository) {
+ return repo(repository).head;
+ }
+
+ @Override
+ public synchronized List tree(Repository repository, String sha, String path) {
+ Map snapshot = repo(repository).snapshots.get(sha);
+ if (snapshot == null) throw new GiteaFailure(404, "NOT_FOUND", "版本不存在", false);
+ String prefix = path.isEmpty() ? "" : path + "/";
+ Map entries = new TreeMap<>();
+ for (Map.Entry file : snapshot.entrySet()) {
+ if (!file.getKey().startsWith(prefix)) continue;
+ String remainder = file.getKey().substring(prefix.length());
+ int separator = remainder.indexOf('/');
+ String name = separator < 0 ? remainder : remainder.substring(0, separator);
+ String entryPath = prefix + name;
+ entries.put(
+ entryPath,
+ separator < 0
+ ? new TreeEntry(
+ entryPath,
+ name,
+ "file",
+ file.getValue().length,
+ blob(file.getValue()))
+ : new TreeEntry(entryPath, name, "dir", 0, ""));
+ }
+ return new ArrayList<>(entries.values());
+ }
+
+ @Override
+ public synchronized StoredFile file(Repository repository, String sha, String path) {
+ Map snapshot = repo(repository).snapshots.get(sha);
+ byte[] bytes = snapshot == null ? null : snapshot.get(path);
+ if (bytes == null) throw new GiteaFailure(404, "NOT_FOUND", "文件不存在", false);
+ return new StoredFile(path, blob(bytes), bytes.clone());
+ }
+
+ @Override
+ public synchronized CommitView commit(
+ Repository repository,
+ List changes,
+ String message,
+ String authorName,
+ String authorCode) {
+ RepoData repo = repo(repository);
+ Map snapshot =
+ repo.head == null ? new TreeMap<>() : new TreeMap<>(repo.snapshots.get(repo.head));
+ for (Change change : changes) {
+ byte[] old = snapshot.get(change.path());
+ if (change.operation().equals("create") && old != null)
+ throw new GiteaFailure(409, "GITEA_CONFLICT", "文件已存在", false);
+ if (!change.operation().equals("create")
+ && (old == null || !blob(old).equals(change.blobSha())))
+ throw new GiteaFailure(409, "GITEA_CONFLICT", "文件版本冲突", false);
+ if (change.operation().equals("delete")) snapshot.remove(change.path());
+ else snapshot.put(change.path(), change.bytes().clone());
+ }
+ repo.head = sha();
+ repo.snapshots.put(repo.head, snapshot);
+ repo.history.addFirst(
+ new HistoryEntry(repo.head, message, authorName, "2026-10-13T00:00:00Z"));
+ if (timeoutNextCommit) {
+ timeoutNextCommit = false;
+ throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "提交结果未知", true);
+ }
+ return new CommitView(repo.head, message);
+ }
+
+ @Override
+ public synchronized PageResponse history(
+ Repository repository, long page, long size) {
+ List history = repo(repository).history;
+ int from = (int) Math.min(history.size(), (page - 1) * size);
+ int to = (int) Math.min(history.size(), from + size);
+ return new PageResponse<>(history.subList(from, to), page, size, history.size());
+ }
+}
diff --git a/community-api/src/test/java/com/linkerbot/community/api/GiteaLiveTest.java b/community-api/src/test/java/com/linkerbot/community/api/GiteaLiveTest.java
new file mode 100644
index 0000000..bfb7dbf
--- /dev/null
+++ b/community-api/src/test/java/com/linkerbot/community/api/GiteaLiveTest.java
@@ -0,0 +1,261 @@
+package com.linkerbot.community.api;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.community.security.CaptchaService;
+import com.linkerbot.community.service.config.CommunityProperties;
+
+import org.junit.jupiter.api.*;
+import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
+import org.springframework.boot.test.context.*;
+import org.springframework.context.annotation.*;
+import org.springframework.http.MediaType;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.web.servlet.*;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
+
+import java.net.URI;
+import java.net.http.*;
+import java.time.Duration;
+import java.util.*;
+
+@SpringBootTest(
+ properties = {
+ "spring.datasource.url=jdbc:h2:mem:live;MODE=MySQL;DB_CLOSE_DELAY=-1",
+ "spring.datasource.username=sa",
+ "spring.datasource.password=",
+ "spring.datasource.driver-class-name=org.h2.Driver",
+ "logging.level.root=INFO",
+ "logging.level.org.springframework=WARN"
+ })
+@ActiveProfiles("test")
+@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
+@Import(GiteaLiveTest.Config.class)
+@EnabledIfEnvironmentVariable(named = "COMMUNITY_LIVE_GITEA", matches = "true")
+class GiteaLiveTest {
+ @TestConfiguration
+ static class Config {
+ @Bean
+ @Primary
+ CaptchaService liveCaptcha(CommunityProperties properties) {
+ return new CaptchaService(properties) {
+ @Override
+ protected String generateAnswer() {
+ return "ABCDE";
+ }
+ };
+ }
+ }
+
+ @Autowired MockMvc mvc;
+ @Autowired ObjectMapper json;
+ @Autowired JdbcTemplate jdbc;
+ @Autowired CommunityProperties config;
+
+ @BeforeEach
+ void schema() throws Exception {
+ SchemaSupport.reset(jdbc);
+ }
+
+ @AfterEach
+ void removeOnlyRepositoriesCreatedByThisTest() throws Exception {
+ HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
+ for (String repo : jdbc.queryForList("SELECT gitea_repo_name FROM project", String.class)) {
+ if (!repo.matches("p_[0-9a-f]{32}")) throw new IllegalStateException("拒绝清理非测试仓库");
+ HttpRequest request =
+ HttpRequest.newBuilder(
+ URI.create(
+ config.getGitea().getBaseUrl()
+ + "/api/v1/repos/"
+ + config.getGitea().getOwner()
+ + "/"
+ + repo))
+ .timeout(Duration.ofSeconds(30))
+ .header("Authorization", "token " + config.getGitea().getToken())
+ .DELETE()
+ .build();
+ assertThat(http.send(request, HttpResponse.BodyHandlers.discarding()).statusCode())
+ .isIn(204, 404);
+ }
+ }
+
+ private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object body)
+ throws Exception {
+ return request.contentType(MediaType.APPLICATION_JSON)
+ .content(json.writeValueAsBytes(body));
+ }
+
+ private MockHttpServletRequestBuilder auth(
+ MockHttpServletRequestBuilder request, String token) {
+ return request.header("Authorization", "Bearer " + token);
+ }
+
+ private JsonNode perform(MockHttpServletRequestBuilder request, int expected) throws Exception {
+ MvcResult result = mvc.perform(request).andReturn();
+ JsonNode response = json.readTree(result.getResponse().getContentAsByteArray());
+ assertThat(result.getResponse().getStatus())
+ .withFailMessage(
+ "请求失败 code=%s requestId=%s",
+ response.path("code").asText(), response.path("requestId").asText())
+ .isEqualTo(expected);
+ return response.path("data");
+ }
+
+ private String login(String email) throws Exception {
+ String captcha = perform(get("/api/auth/captcha"), 200).path("captchaCode").asText();
+ return perform(
+ body(
+ post("/api/auth/login"),
+ Map.of(
+ "email",
+ email,
+ "captchaCode",
+ captcha,
+ "captchaAnswer",
+ "ABCDE")),
+ 200)
+ .path("token")
+ .asText();
+ }
+
+ @Test
+ void realOrganizationRepositoryCommitPublishUploadAndSnapshotFork() throws Exception {
+ String owner = login("live-owner@example.invalid"),
+ other = login("live-fork@example.invalid");
+ String code =
+ perform(
+ body(
+ auth(post("/api/workspace/projects"), owner),
+ Map.of("name", "集成测试临时项目", "projectType", "GENERAL")),
+ 200)
+ .path("projectCode")
+ .asText();
+ String a =
+ perform(auth(get("/api/workspace/projects/" + code + "/tree"), owner), 200)
+ .path("commitSha")
+ .asText();
+ JsonNode before =
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files")
+ .param("path", "README.md"),
+ owner),
+ 200);
+ perform(
+ body(
+ auth(put("/api/workspace/projects/" + code + "/publication"), owner),
+ Map.of("commitSha", a)),
+ 200);
+ JsonNode b =
+ perform(
+ body(
+ auth(post("/api/workspace/projects/" + code + "/commits"), owner),
+ Map.of(
+ "expectedCommitSha",
+ a,
+ "message",
+ "集成验证多文件提交",
+ "changes",
+ List.of(
+ Map.of(
+ "action",
+ "UPDATE_FILE",
+ "path",
+ "README.md",
+ "content",
+ "unpublished"),
+ Map.of("action", "CREATE_DIRECTORY", "path", "空目录"),
+ Map.of(
+ "action",
+ "CREATE_FILE",
+ "path",
+ "源码/hello world.txt",
+ "content",
+ "你好")))),
+ 200);
+ assertThat(
+ perform(
+ get("/api/community/projects/" + code + "/files")
+ .param("path", "README.md"),
+ 200)
+ .path("content")
+ .asText())
+ .isEqualTo(before.path("content").asText());
+ byte[] binary = {0, 1, 2, 3, 4};
+ MockMultipartFile upload =
+ new MockMultipartFile("files", "part.bin", "application/octet-stream", binary);
+ JsonNode c =
+ perform(
+ auth(
+ multipart("/api/workspace/projects/" + code + "/uploads/commit")
+ .file(upload)
+ .param("message", "验证二进制")
+ .param("expectedCommitSha", b.path("commitSha").asText())
+ .param("directory", "模型"),
+ owner),
+ 200);
+ mvc.perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files")
+ .param("path", "模型/part.bin")
+ .param("download", "true"),
+ owner))
+ .andExpect(status().isOk())
+ .andExpect(content().bytes(binary));
+ perform(
+ body(
+ auth(put("/api/workspace/projects/" + code + "/publication"), owner),
+ Map.of("commitSha", c.path("commitSha").asText())),
+ 200);
+ JsonNode fork =
+ perform(
+ body(
+ auth(post("/api/community/projects/" + code + "/forks"), other),
+ Map.of(
+ "name",
+ "集成测试临时副本",
+ "publishedCommitSha",
+ c.path("commitSha").asText())),
+ 200);
+ String copy = fork.path("projectCode").asText();
+ assertThat(
+ perform(
+ auth(
+ get("/api/workspace/projects/" + copy + "/files")
+ .param("path", "源码/hello world.txt"),
+ other),
+ 200)
+ .path("content")
+ .asText())
+ .isEqualTo("你好");
+ mvc.perform(
+ auth(
+ get("/api/workspace/projects/" + copy + "/files")
+ .param("path", "模型/part.bin")
+ .param("download", "true"),
+ other))
+ .andExpect(status().isOk())
+ .andExpect(content().bytes(binary));
+ assertThat(
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/commits"),
+ owner),
+ 200)
+ .path("total")
+ .asLong())
+ .isGreaterThanOrEqualTo(3);
+ perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
+ perform(get("/api/community/projects/" + code), 404);
+ perform(auth(get("/api/workspace/projects/" + copy + "/tree"), other), 200);
+ }
+}
diff --git a/community-api/src/test/java/com/linkerbot/community/api/SchemaSupport.java b/community-api/src/test/java/com/linkerbot/community/api/SchemaSupport.java
new file mode 100644
index 0000000..d123b50
--- /dev/null
+++ b/community-api/src/test/java/com/linkerbot/community/api/SchemaSupport.java
@@ -0,0 +1,28 @@
+package com.linkerbot.community.api;
+
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.regex.*;
+
+final class SchemaSupport {
+ static void reset(JdbcTemplate jdbc) throws IOException {
+ Path path = Path.of("../docs/database.md");
+ if (!Files.exists(path)) path = Path.of("docs/database.md");
+ String content = Files.readString(path);
+ Matcher matcher = Pattern.compile("CREATE TABLE [\\s\\S]*?;").matcher(content);
+ jdbc.execute("DROP ALL OBJECTS");
+ int tables = 0;
+ while (matcher.find()) {
+ String ddl =
+ matcher.group()
+ .replaceAll(" COMMENT '[^']*'", "")
+ .replaceAll("\\) ENGINE=InnoDB[^;]*;", ");");
+ jdbc.execute(ddl);
+ tables++;
+ }
+ if (tables != 4) throw new IllegalStateException("必须只有四张业务表");
+ }
+}
diff --git a/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java b/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java
new file mode 100644
index 0000000..f4d7367
--- /dev/null
+++ b/community-api/src/test/java/com/linkerbot/community/api/WorkflowTest.java
@@ -0,0 +1,601 @@
+package com.linkerbot.community.api;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.community.security.CaptchaService;
+import com.linkerbot.community.service.config.CommunityProperties;
+
+import org.junit.jupiter.api.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
+import org.springframework.boot.test.context.*;
+import org.springframework.context.annotation.*;
+import org.springframework.http.MediaType;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.web.servlet.*;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
+
+import java.util.*;
+import java.util.concurrent.*;
+
+@SpringBootTest(
+ properties = {
+ "spring.datasource.url=jdbc:h2:mem:workflow;MODE=MySQL;DB_CLOSE_DELAY=-1",
+ "spring.datasource.username=sa",
+ "spring.datasource.password=",
+ "spring.datasource.driver-class-name=org.h2.Driver",
+ "logging.level.root=INFO",
+ "logging.level.org.springframework=WARN"
+ })
+@ActiveProfiles("test")
+@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
+@Import(WorkflowTest.Config.class)
+class WorkflowTest {
+ @TestConfiguration
+ static class Config {
+ @Bean
+ @Primary
+ FakeGiteaClient fakeGitea() {
+ return new FakeGiteaClient();
+ }
+
+ @Bean
+ @Primary
+ CaptchaService fixedCaptcha(CommunityProperties properties) {
+ return new CaptchaService(properties) {
+ @Override
+ protected String generateAnswer() {
+ return "ABCDE";
+ }
+ };
+ }
+ }
+
+ @Autowired MockMvc mvc;
+ @Autowired ObjectMapper json;
+ @Autowired JdbcTemplate jdbc;
+ @Autowired FakeGiteaClient gitea;
+
+ @BeforeEach
+ void reset() throws Exception {
+ SchemaSupport.reset(jdbc);
+ gitea.reset();
+ }
+
+ private JsonNode perform(MockHttpServletRequestBuilder builder, int status) throws Exception {
+ String body =
+ mvc.perform(builder)
+ .andExpect(status().is(status))
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
+ return body.isEmpty() ? json.createObjectNode() : json.readTree(body);
+ }
+
+ private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object body)
+ throws Exception {
+ return request.contentType(MediaType.APPLICATION_JSON)
+ .content(json.writeValueAsBytes(body));
+ }
+
+ private JsonNode loginData(String email) throws Exception {
+ String captcha =
+ perform(get("/api/auth/captcha"), 200).path("data").path("captchaCode").asText();
+ return perform(
+ body(
+ post("/api/auth/login"),
+ Map.of(
+ "email",
+ email,
+ "captchaCode",
+ captcha,
+ "captchaAnswer",
+ "abcde")),
+ 200)
+ .path("data");
+ }
+
+ private String login(String email) throws Exception {
+ return loginData(email).path("token").asText();
+ }
+
+ private MockHttpServletRequestBuilder auth(
+ MockHttpServletRequestBuilder request, String token) {
+ return request.header("Authorization", "Bearer " + token);
+ }
+
+ private String create(String token, String name) throws Exception {
+ JsonNode result =
+ perform(
+ body(
+ auth(post("/api/workspace/projects"), token),
+ Map.of(
+ "name",
+ name,
+ "description",
+ "测试项目",
+ "projectType",
+ "GENERAL")),
+ 200);
+ assertThat(result.path("data").has("id")).isFalse();
+ return result.path("data").path("projectCode").asText();
+ }
+
+ private String head(String token, String code) throws Exception {
+ return perform(auth(get("/api/workspace/projects/" + code + "/tree"), token), 200)
+ .path("data")
+ .path("commitSha")
+ .asText();
+ }
+
+ private String commit(String token, String code, String expected, String content)
+ throws Exception {
+ return perform(
+ body(
+ auth(post("/api/workspace/projects/" + code + "/commits"), token),
+ Map.of(
+ "expectedCommitSha",
+ expected,
+ "message",
+ "修改说明",
+ "changes",
+ List.of(
+ Map.of(
+ "action",
+ "UPDATE_FILE",
+ "path",
+ "README.md",
+ "content",
+ content)))),
+ 200)
+ .path("data")
+ .path("commitSha")
+ .asText();
+ }
+
+ private void publish(String token, String code, String sha) throws Exception {
+ perform(
+ body(
+ auth(put("/api/workspace/projects/" + code + "/publication"), token),
+ Map.of("commitSha", sha)),
+ 200);
+ }
+
+ @Test
+ void loginNormalizesEmailAndConsumesCaptchaAndLogout() throws Exception {
+ JsonNode first = loginData("OWNER@example.com");
+ JsonNode second = loginData("owner@example.com");
+ assertThat(first.path("user").path("userCode").asText())
+ .isEqualTo(second.path("user").path("userCode").asText());
+ assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(1L);
+ JsonNode challenge = perform(get("/api/auth/captcha"), 200).path("data");
+ assertThat(challenge.path("image").asText()).startsWith("data:image/png;base64,");
+ Map input =
+ Map.of(
+ "email",
+ "test@example.com",
+ "captchaCode",
+ challenge.path("captchaCode").asText(),
+ "captchaAnswer",
+ "WRONG");
+ perform(body(post("/api/auth/login"), input), 400);
+ perform(
+ body(
+ post("/api/auth/login"),
+ Map.of(
+ "email",
+ "test@example.com",
+ "captchaCode",
+ challenge.path("captchaCode").asText(),
+ "captchaAnswer",
+ "ABCDE")),
+ 400);
+ String token = first.path("token").asText();
+ JsonNode me = perform(auth(get("/api/users/me"), token), 200).path("data");
+ assertThat(me.has("id")).isFalse();
+ perform(auth(post("/api/auth/logout"), token), 200);
+ perform(auth(get("/api/users/me"), token), 401);
+ perform(get("/api/workspace/projects"), 401);
+ }
+
+ @Test
+ void openApiMatchesRoutesAndPublicAuthenticationAndOnlyFourTablesExist() throws Exception {
+ JsonNode spec = perform(get("/v3/api-docs"), 200);
+ assertThat(spec.path("paths").has("/api/workspace/projects")).isTrue();
+ assertThat(spec.path("paths").has("/api/repository-operations/{operationCode}")).isFalse();
+ assertThat(spec.path("paths").path("/api/auth/login").path("post").path("security").size())
+ .isZero();
+ assertThat(spec.path("security").size()).isEqualTo(1);
+ assertThat(
+ jdbc.queryForList(
+ "SELECT table_name FROM information_schema.tables WHERE"
+ + " table_schema='PUBLIC'",
+ String.class))
+ .containsExactlyInAnyOrder(
+ "SYS_USER", "PROJECT", "PROJECT_COMMENT", "PROJECT_LIKE");
+ }
+
+ @Test
+ void publishPinsFilesAndForkCopiesOnlyPublishedSnapshot() throws Exception {
+ String owner = login("owner@example.com");
+ String other = login("other@example.com");
+ String code = create(owner, "测试项目");
+ String a = head(owner, code);
+ publish(owner, code, a);
+ String b = commit(owner, code, a, "未发布内容");
+ JsonNode file =
+ perform(
+ get("/api/community/projects/" + code + "/files")
+ .param("path", "README.md"),
+ 200)
+ .path("data");
+ assertThat(file.path("content").asText()).isEqualTo("initial");
+ assertThat(file.path("commitSha").asText()).isEqualTo(a);
+ perform(
+ get("/api/community/projects/" + code + "/files")
+ .param("path", "README.md")
+ .param("commitSha", b),
+ 400);
+ JsonNode fork =
+ perform(
+ body(
+ auth(
+ post("/api/community/projects/" + code + "/forks"),
+ other),
+ Map.of("publishedCommitSha", a, "name", "我的副本")),
+ 200)
+ .path("data");
+ String copy = fork.path("projectCode").asText();
+ assertThat(fork.path("sourceProjectCode").asText()).isEqualTo(code);
+ assertThat(
+ perform(
+ auth(
+ get("/api/workspace/projects/" + copy + "/files")
+ .param("path", "README.md"),
+ other),
+ 200)
+ .path("data")
+ .path("content")
+ .asText())
+ .isEqualTo("initial");
+ publish(owner, code, b);
+ assertThat(
+ perform(
+ get("/api/community/projects/" + code + "/files")
+ .param("path", "README.md"),
+ 200)
+ .path("data")
+ .path("content")
+ .asText())
+ .isEqualTo("未发布内容");
+ perform(
+ body(
+ auth(post("/api/community/projects/" + code + "/forks"), other),
+ Map.of("publishedCommitSha", a, "name", "过时副本")),
+ 409);
+ perform(auth(delete("/api/workspace/projects/" + code), owner), 200);
+ perform(get("/api/community/projects/" + code), 404);
+ perform(auth(get("/api/workspace/projects/" + copy + "/tree"), other), 200);
+ }
+
+ @Test
+ void permissionsAndFlatCommentsAndIdempotentLikes() throws Exception {
+ String owner = login("owner@example.com");
+ String other = login("other@example.com");
+ String code = create(owner, "权限项目");
+ perform(auth(get("/api/workspace/projects/" + code), other), 404);
+ perform(auth(get("/api/workspace/projects/" + code + "/tree"), other), 404);
+ perform(auth(delete("/api/workspace/projects/" + code), other), 404);
+ perform(get("/api/community/projects/" + code), 404);
+ publish(owner, code, head(owner, code));
+ perform(put("/api/community/projects/" + code + "/like"), 401);
+ perform(auth(put("/api/community/projects/" + code + "/like"), other), 200);
+ perform(auth(put("/api/community/projects/" + code + "/like"), other), 200);
+ assertThat(
+ perform(get("/api/community/projects/" + code), 200)
+ .path("data")
+ .path("likeCount")
+ .asLong())
+ .isEqualTo(1);
+ JsonNode comment =
+ perform(
+ body(
+ auth(
+ post(
+ "/api/community/projects/"
+ + code
+ + "/comments"),
+ other),
+ Map.of("content", "纯文本评论")),
+ 200)
+ .path("data");
+ assertThat(comment.path("author").has("email")).isFalse();
+ assertThat(comment.path("author").has("id")).isFalse();
+ String commentCode = comment.path("commentCode").asText();
+ perform(auth(delete("/api/comments/" + commentCode), owner), 404);
+ perform(auth(delete("/api/comments/" + commentCode), other), 200);
+ assertThat(
+ perform(get("/api/community/projects/" + code + "/comments"), 200)
+ .path("data")
+ .path("total")
+ .asLong())
+ .isZero();
+ perform(auth(delete("/api/community/projects/" + code + "/like"), other), 200);
+ perform(auth(delete("/api/community/projects/" + code + "/like"), other), 200);
+ assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project_like", Long.class)).isZero();
+ perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
+ perform(get("/api/community/projects/" + code), 404);
+ perform(auth(get("/api/workspace/projects/" + code + "/tree"), owner), 200);
+ }
+
+ @Test
+ void directoriesAndBinaryUploadAndDeletionAndPagination() throws Exception {
+ String owner = login("files@example.com");
+ String code = create(owner, "文件项目");
+ String sha = head(owner, code);
+ JsonNode changed =
+ perform(
+ body(
+ auth(
+ post(
+ "/api/workspace/projects/"
+ + code
+ + "/commits"),
+ owner),
+ Map.of(
+ "expectedCommitSha",
+ sha,
+ "message",
+ "创建目录和文件",
+ "changes",
+ List.of(
+ Map.of(
+ "action",
+ "CREATE_DIRECTORY",
+ "path",
+ "models"),
+ Map.of(
+ "action",
+ "CREATE_FILE",
+ "path",
+ "src/main.txt",
+ "content",
+ "hello")))),
+ 200)
+ .path("data");
+ byte[] bytes = {0, 1, 2, 3};
+ MockMultipartFile upload =
+ new MockMultipartFile("files", "model.bin", "application/octet-stream", bytes);
+ JsonNode committed =
+ perform(
+ auth(
+ multipart(
+ "/api/workspace/projects/"
+ + code
+ + "/uploads/commit")
+ .file(upload)
+ .param(
+ "expectedCommitSha",
+ changed.path("commitSha").asText())
+ .param("message", "上传模型")
+ .param("directory", "models"),
+ owner),
+ 200)
+ .path("data");
+ mvc.perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files")
+ .param("path", "models/model.bin")
+ .param("download", "true"),
+ owner))
+ .andExpect(status().isOk())
+ .andExpect(content().bytes(bytes));
+ JsonNode binary =
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files")
+ .param("path", "models/model.bin"),
+ owner),
+ 200)
+ .path("data");
+ assertThat(binary.path("editable").asBoolean()).isFalse();
+ assertThat(binary.path("encoding").asText()).isEqualTo("base64");
+ perform(
+ body(
+ auth(post("/api/workspace/projects/" + code + "/commits"), owner),
+ Map.of(
+ "expectedCommitSha",
+ committed.path("commitSha").asText(),
+ "message",
+ "删除文件",
+ "changes",
+ List.of(Map.of("action", "DELETE_FILE", "path", "src/main.txt")))),
+ 200);
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files")
+ .param("path", "src/main.txt"),
+ owner),
+ 404);
+ assertThat(
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/commits")
+ .param("size", "2"),
+ owner),
+ 200)
+ .path("data")
+ .path("items")
+ .size())
+ .isEqualTo(2);
+ perform(auth(get("/api/workspace/projects").param("size", "101"), owner), 400);
+ }
+
+ @Test
+ void staleAndConcurrentSubmissionsCannotOverwrite() throws Exception {
+ String owner = login("concurrent@example.com");
+ String code = create(owner, "并发项目");
+ String sha = head(owner, code);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Callable submit =
+ () ->
+ mvc.perform(
+ body(
+ auth(
+ post(
+ "/api/workspace/projects/"
+ + code
+ + "/commits"),
+ owner),
+ Map.of(
+ "expectedCommitSha",
+ sha,
+ "message",
+ "并发提交",
+ "changes",
+ List.of(
+ Map.of(
+ "action",
+ "UPDATE_FILE",
+ "path",
+ "README.md",
+ "content",
+ "new")))))
+ .andReturn()
+ .getResponse()
+ .getStatus();
+ List> results = executor.invokeAll(List.of(submit, submit));
+ assertThat(List.of(results.get(0).get(), results.get(1).get()))
+ .containsExactlyInAnyOrder(200, 409);
+ } finally {
+ executor.shutdownNow();
+ }
+ perform(
+ body(
+ auth(put("/api/workspace/projects/" + code + "/publication"), owner),
+ Map.of("commitSha", sha)),
+ 409);
+ }
+
+ @Test
+ void unsafePathsOversizedTextAndUnsupportedTypeAreRejected() throws Exception {
+ String owner = login("paths@example.com");
+ perform(
+ body(
+ auth(post("/api/workspace/projects"), owner),
+ Map.of("name", "x", "projectType", "UNKNOWN")),
+ 400);
+ String code = create(owner, "路径项目");
+ String sha = head(owner, code);
+ for (String path : List.of("../secret", "/tmp/secret", ".git/config", "a/../b", "a\\b")) {
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files").param("path", path),
+ owner),
+ 400);
+ }
+ perform(
+ body(
+ auth(post("/api/workspace/projects/" + code + "/commits"), owner),
+ Map.of(
+ "expectedCommitSha",
+ sha,
+ "message",
+ "大文件",
+ "changes",
+ List.of(
+ Map.of(
+ "action",
+ "CREATE_FILE",
+ "path",
+ "large.txt",
+ "content",
+ "x".repeat(1048577))))),
+ 413);
+ }
+
+ @Test
+ void unknownRemoteWritesAreNotRepeatedAndFailedCreatesRemainVisible() throws Exception {
+ String owner = login("failure@example.com");
+ gitea.failNextCreate = true;
+ JsonNode failure =
+ perform(
+ body(
+ auth(post("/api/workspace/projects"), owner),
+ Map.of("name", "失败项目", "projectType", "GENERAL")),
+ 502);
+ String failed = failure.path("data").path("projectCode").asText();
+ assertThat(
+ perform(auth(get("/api/workspace/projects/" + failed), owner), 200)
+ .path("data")
+ .path("repoStatus")
+ .asText())
+ .isEqualTo("FAILED");
+ gitea.timeoutNextCreate = true;
+ JsonNode pending =
+ perform(
+ body(
+ auth(post("/api/workspace/projects"), owner),
+ Map.of("name", "待核对项目", "projectType", "GENERAL")),
+ 504);
+ assertThat(
+ perform(
+ auth(
+ get(
+ "/api/workspace/projects/"
+ + pending.path("data")
+ .path("projectCode")
+ .asText()),
+ owner),
+ 200)
+ .path("data")
+ .path("repoStatus")
+ .asText())
+ .isEqualTo("CREATING");
+ String code = create(owner, "超时项目");
+ String sha = head(owner, code);
+ gitea.timeoutNextCommit = true;
+ Map request =
+ Map.of(
+ "expectedCommitSha",
+ sha,
+ "message",
+ "超时提交",
+ "changes",
+ List.of(
+ Map.of(
+ "action",
+ "UPDATE_FILE",
+ "path",
+ "README.md",
+ "content",
+ "实际成功")));
+ perform(
+ body(auth(post("/api/workspace/projects/" + code + "/commits"), owner), request),
+ 504);
+ perform(
+ body(auth(post("/api/workspace/projects/" + code + "/commits"), owner), request),
+ 409);
+ assertThat(
+ perform(
+ auth(
+ get("/api/workspace/projects/" + code + "/files")
+ .param("path", "README.md"),
+ owner),
+ 200)
+ .path("data")
+ .path("content")
+ .asText())
+ .isEqualTo("实际成功");
+ perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
+ perform(auth(delete("/api/workspace/projects/" + code), owner), 200);
+ }
+}
diff --git a/community-bean/pom.xml b/community-bean/pom.xml
new file mode 100644
index 0000000..3bcfe1b
--- /dev/null
+++ b/community-bean/pom.xml
@@ -0,0 +1,21 @@
+
+
+ 4.0.0
+
+ com.linkerbot
+ community
+ 0.0.1-SNAPSHOT
+
+ community-bean
+
+
+ com.baomidou
+ mybatis-plus-core
+ ${mybatis-plus.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-validation
+
+
+
diff --git a/community-bean/src/main/java/com/linkerbot/community/bean/Contracts.java b/community-bean/src/main/java/com/linkerbot/community/bean/Contracts.java
new file mode 100644
index 0000000..20981f2
--- /dev/null
+++ b/community-bean/src/main/java/com/linkerbot/community/bean/Contracts.java
@@ -0,0 +1,91 @@
+package com.linkerbot.community.bean;
+
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.*;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+public final class Contracts {
+ private Contracts() {}
+
+ public record LoginRequest(
+ @NotBlank @Email @Size(max = 254) String email,
+ @NotBlank String captchaCode,
+ @NotBlank String captchaAnswer) {}
+
+ public record UserView(String userCode, String nickname, String email) {}
+
+ public record PublicUser(String userCode, String nickname) {}
+
+ public record LoginView(String token, String tokenType, long expiresIn, UserView user) {}
+
+ public record CaptchaView(String captchaCode, String image, long expiresIn) {}
+
+ public record ProjectInput(
+ @NotBlank @Size(max = 100) String name,
+ @Size(max = 2000) String description,
+ @NotBlank @Size(max = 64) String projectType) {}
+
+ public record PublicationInput(@NotBlank String commitSha) {}
+
+ public record ForkInput(
+ @NotBlank String publishedCommitSha, @NotBlank @Size(max = 100) String name) {}
+
+ public record CommentInput(@NotBlank @Size(max = 2000) String content) {}
+
+ public record TypeView(String code, String name) {}
+
+ public record ProjectView(
+ String projectCode,
+ String name,
+ String description,
+ String projectType,
+ PublicUser owner,
+ String repoStatus,
+ String publishStatus,
+ String publishedCommitSha,
+ LocalDateTime publishedAt,
+ String sourceProjectCode,
+ String sourceCommitSha,
+ long likeCount,
+ long commentCount,
+ boolean liked,
+ LocalDateTime createdAt,
+ LocalDateTime updatedAt) {}
+
+ public record CommentView(
+ String commentCode, PublicUser author, String content, LocalDateTime createdAt) {}
+
+ public enum ChangeAction {
+ CREATE_FILE,
+ UPDATE_FILE,
+ DELETE_FILE,
+ CREATE_DIRECTORY
+ }
+
+ public record FileChange(@NotNull ChangeAction action, @NotBlank String path, String content) {}
+
+ public record CommitInput(
+ @NotBlank String expectedCommitSha,
+ @NotBlank @Size(max = 1000) String message,
+ @NotEmpty @Size(max = 500) List<@Valid FileChange> changes) {}
+
+ public record CommitView(String commitSha, String message) {}
+
+ public record TreeEntry(String path, String name, String type, long size, String blobSha) {}
+
+ public record TreeView(String commitSha, String path, List entries) {}
+
+ public record FileView(
+ String commitSha,
+ String path,
+ String blobSha,
+ long size,
+ String encoding,
+ String content,
+ boolean editable) {}
+
+ public record HistoryEntry(
+ String commitSha, String message, String authorName, String authorDate) {}
+}
diff --git a/community-bean/src/main/java/com/linkerbot/community/bean/entity/BaseEntity.java b/community-bean/src/main/java/com/linkerbot/community/bean/entity/BaseEntity.java
new file mode 100644
index 0000000..c0e976f
--- /dev/null
+++ b/community-bean/src/main/java/com/linkerbot/community/bean/entity/BaseEntity.java
@@ -0,0 +1,19 @@
+package com.linkerbot.community.bean.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import java.time.LocalDateTime;
+
+@Getter
+@Setter
+public abstract class BaseEntity {
+ @TableId(type = IdType.AUTO)
+ private Long id;
+
+ private LocalDateTime createdAt;
+ private LocalDateTime updatedAt;
+}
diff --git a/community-bean/src/main/java/com/linkerbot/community/bean/entity/Project.java b/community-bean/src/main/java/com/linkerbot/community/bean/entity/Project.java
new file mode 100644
index 0000000..d726f5d
--- /dev/null
+++ b/community-bean/src/main/java/com/linkerbot/community/bean/entity/Project.java
@@ -0,0 +1,29 @@
+package com.linkerbot.community.bean.entity;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import java.time.LocalDateTime;
+
+@Getter
+@Setter
+@TableName("project")
+public class Project extends BaseEntity {
+ private String projectCode;
+ private Long ownerUserId;
+ private String name;
+ private String description;
+ private String projectType;
+ private Long giteaRepoId;
+ private String giteaOwner;
+ private String giteaRepoName;
+ private String repoStatus;
+ private String publishStatus;
+ private String publishedCommitSha;
+ private LocalDateTime publishedAt;
+ private Long sourceProjectId;
+ private String sourceCommitSha;
+ private Boolean deleted;
+}
diff --git a/community-bean/src/main/java/com/linkerbot/community/bean/entity/ProjectComment.java b/community-bean/src/main/java/com/linkerbot/community/bean/entity/ProjectComment.java
new file mode 100644
index 0000000..7acff7b
--- /dev/null
+++ b/community-bean/src/main/java/com/linkerbot/community/bean/entity/ProjectComment.java
@@ -0,0 +1,17 @@
+package com.linkerbot.community.bean.entity;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+@TableName("project_comment")
+public class ProjectComment extends BaseEntity {
+ private String commentCode;
+ private Long projectId;
+ private Long userId;
+ private String content;
+ private Boolean deleted;
+}
diff --git a/community-bean/src/main/java/com/linkerbot/community/bean/entity/ProjectLike.java b/community-bean/src/main/java/com/linkerbot/community/bean/entity/ProjectLike.java
new file mode 100644
index 0000000..68f37bd
--- /dev/null
+++ b/community-bean/src/main/java/com/linkerbot/community/bean/entity/ProjectLike.java
@@ -0,0 +1,22 @@
+package com.linkerbot.community.bean.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import java.time.LocalDateTime;
+
+@Getter
+@Setter
+@TableName("project_like")
+public class ProjectLike {
+ @TableId(type = IdType.AUTO)
+ private Long id;
+
+ private Long projectId;
+ private Long userId;
+ private LocalDateTime createdAt;
+}
diff --git a/community-bean/src/main/java/com/linkerbot/community/bean/entity/User.java b/community-bean/src/main/java/com/linkerbot/community/bean/entity/User.java
new file mode 100644
index 0000000..846b7cf
--- /dev/null
+++ b/community-bean/src/main/java/com/linkerbot/community/bean/entity/User.java
@@ -0,0 +1,16 @@
+package com.linkerbot.community.bean.entity;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+@TableName("sys_user")
+public class User extends BaseEntity {
+ private String userCode;
+ private String email;
+ private String nickname;
+ private String status;
+}
diff --git a/community-common/pom.xml b/community-common/pom.xml
new file mode 100644
index 0000000..4124d10
--- /dev/null
+++ b/community-common/pom.xml
@@ -0,0 +1,20 @@
+
+
+ 4.0.0
+
+ com.linkerbot
+ community
+ 0.0.1-SNAPSHOT
+
+ community-common
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-validation
+
+
+
diff --git a/community-common/src/main/java/com/linkerbot/community/common/ApiResponse.java b/community-common/src/main/java/com/linkerbot/community/common/ApiResponse.java
new file mode 100644
index 0000000..6cd2c4c
--- /dev/null
+++ b/community-common/src/main/java/com/linkerbot/community/common/ApiResponse.java
@@ -0,0 +1,14 @@
+package com.linkerbot.community.common;
+
+import org.slf4j.MDC;
+
+public record ApiResponse(String code, String message, T data, String requestId) {
+ public static ApiResponse success(T data) {
+ return new ApiResponse<>("OK", "成功", data, MDC.get("requestId"));
+ }
+
+ public static ApiResponse