社区初始化
This commit is contained in:
@@ -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
|
||||
@@ -0,0 +1,5 @@
|
||||
.idea/
|
||||
**/target/
|
||||
.env
|
||||
.DS_Store
|
||||
logs/
|
||||
@@ -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。结果不明或数据库回写失败需要人工核对;不提供后台自动恢复、无条件自动重试或跨重启完整幂等。具体恢复方式见接口文档。
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>community-api</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community-security</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -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<CaptchaView> captcha() {
|
||||
return ApiResponse.success(captcha.issue());
|
||||
}
|
||||
|
||||
@PostMapping("/api/auth/login")
|
||||
@Operation(summary = "邮箱和图片验证码登录,首次自动创建用户")
|
||||
@SecurityRequirements
|
||||
public ApiResponse<LoginView> 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<Void> 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<UserView> me() {
|
||||
return ApiResponse.success(users.view(users.require(CurrentUser.required())));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<List<TypeView>> types() {
|
||||
return ApiResponse.success(projects.types());
|
||||
}
|
||||
|
||||
@GetMapping("/api/community/projects")
|
||||
@Operation(summary = "已发布项目列表,支持类型和关键词筛选")
|
||||
@SecurityRequirements
|
||||
public ApiResponse<PageResponse<ProjectView>> 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<ProjectView> 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<TreeView> 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<ProjectView> 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<PageResponse<CommentView>> 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<CommentView> 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<Void> deleteComment(@PathVariable String commentCode) {
|
||||
interactions.deleteComment(CurrentUser.required(), commentCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@PutMapping("/api/community/projects/{projectCode}/like")
|
||||
@Operation(summary = "幂等点赞")
|
||||
public ApiResponse<Void> like(@PathVariable String projectCode) {
|
||||
interactions.like(CurrentUser.required(), projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@DeleteMapping("/api/community/projects/{projectCode}/like")
|
||||
@Operation(summary = "幂等取消点赞")
|
||||
public ApiResponse<Void> unlike(@PathVariable String projectCode) {
|
||||
interactions.unlike(CurrentUser.required(), projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<PageResponse<ProjectView>> 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<ProjectView> create(@Valid @RequestBody ProjectInput input) {
|
||||
return ApiResponse.success(projects.create(CurrentUser.required(), input));
|
||||
}
|
||||
|
||||
@GetMapping("/{projectCode}")
|
||||
@Operation(summary = "我的项目详情")
|
||||
public ApiResponse<ProjectView> detail(@PathVariable String projectCode) {
|
||||
long user = CurrentUser.required();
|
||||
return ApiResponse.success(projects.view(projects.owner(user, projectCode), user));
|
||||
}
|
||||
|
||||
@PatchMapping("/{projectCode}")
|
||||
@Operation(summary = "修改名称、描述和类型")
|
||||
public ApiResponse<ProjectView> update(
|
||||
@PathVariable String projectCode, @Valid @RequestBody ProjectInput input) {
|
||||
return ApiResponse.success(projects.update(CurrentUser.required(), projectCode, input));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{projectCode}")
|
||||
@Operation(summary = "逻辑删除项目并撤回社区")
|
||||
public ApiResponse<Void> delete(@PathVariable String projectCode) {
|
||||
projects.delete(CurrentUser.required(), projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@GetMapping("/{projectCode}/tree")
|
||||
@Operation(summary = "读取目录,可指定本项目 Commit")
|
||||
public ApiResponse<TreeView> 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<byte[]> 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<CommitView> 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<PageResponse<HistoryEntry>> 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<CommitView> upload(
|
||||
@PathVariable String projectCode,
|
||||
@RequestParam String expectedCommitSha,
|
||||
@RequestParam String message,
|
||||
@RequestParam(defaultValue = "") String directory,
|
||||
@RequestParam("files") List<MultipartFile> uploaded,
|
||||
@RequestParam(required = false) List<String> paths) {
|
||||
return ApiResponse.success(
|
||||
files.upload(
|
||||
CurrentUser.required(),
|
||||
projectCode,
|
||||
expectedCommitSha,
|
||||
message,
|
||||
directory,
|
||||
uploaded,
|
||||
paths));
|
||||
}
|
||||
|
||||
@PutMapping("/{projectCode}/publication")
|
||||
@Operation(summary = "发布或手动更新社区文件版本")
|
||||
public ApiResponse<ProjectView> 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<Void> withdraw(@PathVariable String projectCode) {
|
||||
projects.withdraw(CurrentUser.required(), projectCode);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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<String, Map<String, byte[]>> snapshots = new HashMap<>();
|
||||
List<HistoryEntry> history = new ArrayList<>();
|
||||
}
|
||||
|
||||
private final Map<Long, RepoData> 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<TreeEntry> tree(Repository repository, String sha, String path) {
|
||||
Map<String, byte[]> snapshot = repo(repository).snapshots.get(sha);
|
||||
if (snapshot == null) throw new GiteaFailure(404, "NOT_FOUND", "版本不存在", false);
|
||||
String prefix = path.isEmpty() ? "" : path + "/";
|
||||
Map<String, TreeEntry> entries = new TreeMap<>();
|
||||
for (Map.Entry<String, byte[]> 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<String, byte[]> 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<Change> changes,
|
||||
String message,
|
||||
String authorName,
|
||||
String authorCode) {
|
||||
RepoData repo = repo(repository);
|
||||
Map<String, byte[]> 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<HistoryEntry> history(
|
||||
Repository repository, long page, long size) {
|
||||
List<HistoryEntry> 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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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("必须只有四张业务表");
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> 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<Integer> 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<Future<Integer>> 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<String, Object> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>community-bean</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-core</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -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<TreeEntry> 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) {}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>community-common</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
|
||||
public record ApiResponse<T>(String code, String message, T data, String requestId) {
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
return new ApiResponse<>("OK", "成功", data, MDC.get("requestId"));
|
||||
}
|
||||
|
||||
public static ApiResponse<Object> failure(BusinessException error) {
|
||||
return new ApiResponse<>(
|
||||
error.code(), error.getMessage(), error.details(), MDC.get("requestId"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
public class BusinessException extends RuntimeException {
|
||||
private final int status;
|
||||
private final String code;
|
||||
private final Object details;
|
||||
|
||||
public BusinessException(int status, String code, String message) {
|
||||
this(status, code, message, null);
|
||||
}
|
||||
|
||||
public BusinessException(int status, String code, String message, Object details) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
}
|
||||
|
||||
public int status() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public String code() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public Object details() {
|
||||
return details;
|
||||
}
|
||||
|
||||
public static BusinessException badRequest(String message) {
|
||||
return new BusinessException(400, "BAD_REQUEST", message);
|
||||
}
|
||||
|
||||
public static BusinessException notFound() {
|
||||
return new BusinessException(404, "NOT_FOUND", "资源不存在或不可访问");
|
||||
}
|
||||
|
||||
public static BusinessException conflict(String message) {
|
||||
return new BusinessException(409, "CONFLICT", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public final class Codes {
|
||||
private Codes() {}
|
||||
|
||||
public static String next() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public final class FilePaths {
|
||||
private FilePaths() {}
|
||||
|
||||
public static String directory(String path) {
|
||||
return path == null || path.isEmpty() ? "" : file(path);
|
||||
}
|
||||
|
||||
public static String file(String path) {
|
||||
if (path == null
|
||||
|| path.isBlank()
|
||||
|| path.length() > 1024
|
||||
|| path.startsWith("/")
|
||||
|| path.contains("\\")
|
||||
|| path.chars().anyMatch(c -> c < 32 || c == 127)) {
|
||||
throw BusinessException.badRequest("文件路径必须是合法的相对路径");
|
||||
}
|
||||
for (String part : path.split("/", -1)) {
|
||||
if (part.isEmpty()
|
||||
|| part.equals(".")
|
||||
|| part.equals("..")
|
||||
|| part.toLowerCase(Locale.ROOT).equals(".git")
|
||||
|| part.contains(":")) {
|
||||
throw BusinessException.badRequest("文件路径包含禁止的目录或字符");
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public static String sha(String sha) {
|
||||
if (sha == null || !sha.matches("[0-9a-fA-F]{40}|[0-9a-fA-F]{64}"))
|
||||
throw BusinessException.badRequest("Commit SHA 格式错误");
|
||||
return sha.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.HandlerMethodValidationException;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.support.MissingServletRequestPartException;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ResponseEntity<ApiResponse<Object>> business(BusinessException error) {
|
||||
return ResponseEntity.status(error.status()).body(ApiResponse.failure(error));
|
||||
}
|
||||
|
||||
@ExceptionHandler({
|
||||
MethodArgumentNotValidException.class,
|
||||
ConstraintViolationException.class,
|
||||
HttpMessageNotReadableException.class,
|
||||
HandlerMethodValidationException.class,
|
||||
MissingServletRequestParameterException.class,
|
||||
MethodArgumentTypeMismatchException.class,
|
||||
MissingServletRequestPartException.class
|
||||
})
|
||||
public ResponseEntity<ApiResponse<Object>> invalid(Exception error) {
|
||||
return business(BusinessException.badRequest("请求参数不合法"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<ApiResponse<Object>> oversized(Exception error) {
|
||||
return business(new BusinessException(413, "UPLOAD_TOO_LARGE", "上传超过大小限制"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ResponseEntity<ApiResponse<Object>> method(Exception error) {
|
||||
return business(new BusinessException(405, "METHOD_NOT_ALLOWED", "不支持此请求方法"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ResponseEntity<ApiResponse<Object>> media(Exception error) {
|
||||
return business(new BusinessException(415, "UNSUPPORTED_MEDIA_TYPE", "请求内容类型不支持"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public ResponseEntity<ApiResponse<Object>> missing(Exception error) {
|
||||
return business(BusinessException.notFound());
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Object>> unexpected(Exception error) {
|
||||
log.error("未处理异常 type={}", error.getClass().getName());
|
||||
return business(new BusinessException(500, "INTERNAL_ERROR", "服务暂时不可用,请提供 requestId 排查"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PageResponse<T>(List<T> items, long page, long size, long total) {}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.linkerbot.community.common;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestIdFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String requestId = Codes.next();
|
||||
MDC.put("requestId", requestId);
|
||||
response.setHeader("X-Request-Id", requestId);
|
||||
try {
|
||||
chain.doFilter(request, response);
|
||||
} finally {
|
||||
MDC.remove("requestId");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<springProperty scope="context" name="APP_NAME" source="spring.application.name" defaultValue="community"/>
|
||||
<springProperty scope="context" name="LOG_PATH" source="logging.file.path" defaultValue="logs"/>
|
||||
|
||||
<property name="LOG_PATTERN"
|
||||
value="%d{yyyy-MM-dd HH:mm:ss.SSS,Asia/Shanghai} [%thread] %-5level [%X{requestId:-}] %logger{36} - %msg%n%ex"/>
|
||||
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${LOG_PATTERN}</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="APP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/${APP_NAME}.log</file>
|
||||
<encoder>
|
||||
<pattern>${LOG_PATTERN}</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/archive/${APP_NAME}.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>100MB</maxFileSize>
|
||||
<maxHistory>30</maxHistory>
|
||||
<totalSizeCap>10GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/${APP_NAME}-error.log</file>
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>ERROR</level>
|
||||
</filter>
|
||||
<encoder>
|
||||
<pattern>${LOG_PATTERN}</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/archive/${APP_NAME}-error.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>50MB</maxFileSize>
|
||||
<maxHistory>60</maxHistory>
|
||||
<totalSizeCap>5GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="APP_FILE"/>
|
||||
<appender-ref ref="ERROR_FILE"/>
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>community-security</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community-service</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.UserService;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BearerTokenFilter extends OncePerRequestFilter {
|
||||
private final TokenService tokens;
|
||||
private final UserService users;
|
||||
private final ObjectMapper json;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
try {
|
||||
Long id = tokens.resolve(header.substring(7));
|
||||
if (id == null) throw new BusinessException(401, "UNAUTHORIZED", "登录已失效,请重新登录");
|
||||
users.require(id);
|
||||
UsernamePasswordAuthenticationToken auth =
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
new CurrentUser.Principal(id),
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} catch (BusinessException error) {
|
||||
response.setStatus(error.status());
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
json.writeValue(response.getOutputStream(), ApiResponse.failure(error));
|
||||
return;
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.linkerbot.community.bean.Contracts.CaptchaView;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
@Service
|
||||
public class CaptchaService {
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final Cache<String, String> challenges;
|
||||
private final CommunityProperties config;
|
||||
|
||||
public CaptchaService(CommunityProperties config) {
|
||||
this.config = config;
|
||||
this.challenges =
|
||||
Caffeine.newBuilder()
|
||||
.maximumSize(10000)
|
||||
.expireAfterWrite(config.getCaptchaTtl())
|
||||
.build();
|
||||
}
|
||||
|
||||
protected String generateAnswer() {
|
||||
String alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < 5; i++)
|
||||
result.append(alphabet.charAt(random.nextInt(alphabet.length())));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public CaptchaView issue() {
|
||||
String answer = generateAnswer();
|
||||
BufferedImage image = new BufferedImage(180, 60, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D graphics = image.createGraphics();
|
||||
try {
|
||||
graphics.setColor(new Color(245, 247, 250));
|
||||
graphics.fillRect(0, 0, 180, 60);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
graphics.setColor(
|
||||
new Color(random.nextInt(160), random.nextInt(160), random.nextInt(160)));
|
||||
graphics.drawLine(
|
||||
random.nextInt(180),
|
||||
random.nextInt(60),
|
||||
random.nextInt(180),
|
||||
random.nextInt(60));
|
||||
}
|
||||
graphics.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 30));
|
||||
for (int i = 0; i < answer.length(); i++) {
|
||||
graphics.setColor(
|
||||
new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100)));
|
||||
graphics.drawString(
|
||||
String.valueOf(answer.charAt(i)), 15 + i * 30, 38 + random.nextInt(8));
|
||||
}
|
||||
} finally {
|
||||
graphics.dispose();
|
||||
}
|
||||
try (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
|
||||
ImageIO.write(image, "png", bytes);
|
||||
String code = Codes.next();
|
||||
challenges.put(code, answer);
|
||||
return new CaptchaView(
|
||||
code,
|
||||
"data:image/png;base64,"
|
||||
+ Base64.getEncoder().encodeToString(bytes.toByteArray()),
|
||||
config.getCaptchaTtl().toSeconds());
|
||||
} catch (IOException error) {
|
||||
throw new BusinessException(500, "CAPTCHA_ERROR", "验证码生成失败");
|
||||
}
|
||||
}
|
||||
|
||||
public void verify(String code, String answer) {
|
||||
String expected = challenges.asMap().remove(code);
|
||||
String actual = answer == null ? "" : answer.trim().toUpperCase(Locale.ROOT);
|
||||
if (expected == null
|
||||
|| !MessageDigest.isEqual(
|
||||
expected.getBytes(StandardCharsets.UTF_8),
|
||||
actual.getBytes(StandardCharsets.UTF_8)))
|
||||
throw new BusinessException(400, "CAPTCHA_INVALID", "图片验证码错误、已使用或已过期");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public final class CurrentUser {
|
||||
private CurrentUser() {}
|
||||
|
||||
public record Principal(long userId) {}
|
||||
|
||||
public static Long optional() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
return auth != null && auth.getPrincipal() instanceof Principal principal
|
||||
? principal.userId()
|
||||
: null;
|
||||
}
|
||||
|
||||
public static long required() {
|
||||
Long id = optional();
|
||||
if (id == null) throw new BusinessException(401, "UNAUTHORIZED", "请先登录");
|
||||
return id;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.common.*;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfiguration {
|
||||
@Bean
|
||||
public FilterRegistrationBean<BearerTokenFilter> disableServletRegistration(
|
||||
BearerTokenFilter filter) {
|
||||
FilterRegistrationBean<BearerTokenFilter> registration =
|
||||
new FilterRegistrationBean<>(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(
|
||||
HttpSecurity http, BearerTokenFilter tokenFilter, ObjectMapper json) throws Exception {
|
||||
http.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(
|
||||
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.formLogin(form -> form.disable())
|
||||
.httpBasic(basic -> basic.disable())
|
||||
.logout(logout -> logout.disable())
|
||||
.authorizeHttpRequests(
|
||||
auth ->
|
||||
auth.requestMatchers(
|
||||
"/api/auth/captcha",
|
||||
"/api/auth/login",
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html",
|
||||
"/error")
|
||||
.permitAll()
|
||||
.requestMatchers(
|
||||
HttpMethod.GET,
|
||||
"/api/community/**",
|
||||
"/api/project-types")
|
||||
.permitAll()
|
||||
.requestMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
.exceptionHandling(
|
||||
errors ->
|
||||
errors.authenticationEntryPoint(
|
||||
(request, response, error) -> {
|
||||
response.setStatus(401);
|
||||
response.setContentType(
|
||||
"application/json;charset=UTF-8");
|
||||
json.writeValue(
|
||||
response.getOutputStream(),
|
||||
ApiResponse.failure(
|
||||
new BusinessException(
|
||||
401,
|
||||
"UNAUTHORIZED",
|
||||
"请先登录")));
|
||||
})
|
||||
.accessDeniedHandler(
|
||||
(request, response, error) -> {
|
||||
response.setStatus(403);
|
||||
response.setContentType(
|
||||
"application/json;charset=UTF-8");
|
||||
json.writeValue(
|
||||
response.getOutputStream(),
|
||||
ApiResponse.failure(
|
||||
new BusinessException(
|
||||
403,
|
||||
"FORBIDDEN",
|
||||
"无权访问")));
|
||||
}))
|
||||
.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class TokenService {
|
||||
private final Cache<String, Long> sessions;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public TokenService(CommunityProperties config) {
|
||||
sessions =
|
||||
Caffeine.newBuilder()
|
||||
.maximumSize(10000)
|
||||
.expireAfterWrite(config.getTokenTtl())
|
||||
.build();
|
||||
}
|
||||
|
||||
public String issue(long userId) {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
sessions.put(token, userId);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Long resolve(String token) {
|
||||
return sessions.getIfPresent(token);
|
||||
}
|
||||
|
||||
public void revoke(String token) {
|
||||
if (token != null) sessions.invalidate(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.linkerbot.community.security;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
class SessionTest {
|
||||
@Test
|
||||
void expiredCaptchaAndTokenCannotBeUsed() throws Exception {
|
||||
CommunityProperties properties = new CommunityProperties();
|
||||
properties.setCaptchaTtl(Duration.ofMillis(1));
|
||||
properties.setTokenTtl(Duration.ofMillis(1));
|
||||
CaptchaService captcha =
|
||||
new CaptchaService(properties) {
|
||||
@Override
|
||||
protected String generateAnswer() {
|
||||
return "ABCDE";
|
||||
}
|
||||
};
|
||||
String code = captcha.issue().captchaCode();
|
||||
TokenService tokens = new TokenService(properties);
|
||||
String token = tokens.issue(1L);
|
||||
Thread.sleep(20);
|
||||
assertThatThrownBy(() -> captcha.verify(code, "ABCDE"))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
assertThat(tokens.resolve(token)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokensAreRandomAndRevocable() {
|
||||
TokenService tokens = new TokenService(new CommunityProperties());
|
||||
String a = tokens.issue(1L);
|
||||
String b = tokens.issue(1L);
|
||||
assertThat(a).isNotEqualTo(b);
|
||||
assertThat(tokens.resolve(a)).isEqualTo(1L);
|
||||
tokens.revoke(a);
|
||||
assertThat(tokens.resolve(a)).isNull();
|
||||
assertThat(tokens.resolve(b)).isEqualTo(1L);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>community-service</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community-common</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community-bean</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-jsqlparser</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.linkerbot.community.service;
|
||||
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.bean.entity.Project;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
import com.linkerbot.community.service.gitea.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.*;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FileService {
|
||||
private static final Logger log = LoggerFactory.getLogger(FileService.class);
|
||||
private final ProjectService projects;
|
||||
private final UserService users;
|
||||
private final GiteaClient gitea;
|
||||
private final CommunityProperties config;
|
||||
|
||||
public TreeView ownerTree(long userId, String code, String path, String commitSha) {
|
||||
Project project = projects.readyOwner(userId, code);
|
||||
String sha =
|
||||
commitSha == null
|
||||
? gitea.head(projects.repository(project))
|
||||
: FilePaths.sha(commitSha);
|
||||
return tree(project, sha, path);
|
||||
}
|
||||
|
||||
public TreeView communityTree(String code, String path) {
|
||||
Project project = projects.published(code);
|
||||
return tree(project, project.getPublishedCommitSha(), path);
|
||||
}
|
||||
|
||||
private TreeView tree(Project project, String sha, String path) {
|
||||
String normalized = FilePaths.directory(path);
|
||||
return new TreeView(
|
||||
sha, normalized, gitea.tree(projects.repository(project), sha, normalized));
|
||||
}
|
||||
|
||||
public GiteaClient.StoredFile ownerFile(
|
||||
long userId, String code, String path, String commitSha) {
|
||||
Project project = projects.readyOwner(userId, code);
|
||||
String sha =
|
||||
commitSha == null
|
||||
? gitea.head(projects.repository(project))
|
||||
: FilePaths.sha(commitSha);
|
||||
return gitea.file(projects.repository(project), sha, FilePaths.file(path));
|
||||
}
|
||||
|
||||
public FileView ownerFileView(long userId, String code, String path, String commitSha) {
|
||||
Project project = projects.readyOwner(userId, code);
|
||||
String sha =
|
||||
commitSha == null
|
||||
? gitea.head(projects.repository(project))
|
||||
: FilePaths.sha(commitSha);
|
||||
return fileView(sha, gitea.file(projects.repository(project), sha, FilePaths.file(path)));
|
||||
}
|
||||
|
||||
public GiteaClient.StoredFile communityFile(String code, String path) {
|
||||
Project project = projects.published(code);
|
||||
return gitea.file(
|
||||
projects.repository(project),
|
||||
project.getPublishedCommitSha(),
|
||||
FilePaths.file(path));
|
||||
}
|
||||
|
||||
public FileView communityFileView(String code, String path) {
|
||||
Project project = projects.published(code);
|
||||
return fileView(
|
||||
project.getPublishedCommitSha(),
|
||||
gitea.file(
|
||||
projects.repository(project),
|
||||
project.getPublishedCommitSha(),
|
||||
FilePaths.file(path)));
|
||||
}
|
||||
|
||||
private String text(byte[] bytes) {
|
||||
if (bytes.length > config.getMaxTextBytes()) return null;
|
||||
for (byte value : bytes) if (value == 0) return null;
|
||||
try {
|
||||
return StandardCharsets.UTF_8
|
||||
.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(bytes))
|
||||
.toString();
|
||||
} catch (CharacterCodingException error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private FileView fileView(String sha, GiteaClient.StoredFile file) {
|
||||
String content = text(file.bytes());
|
||||
return new FileView(
|
||||
sha,
|
||||
file.path(),
|
||||
file.blobSha(),
|
||||
file.bytes().length,
|
||||
content == null ? "base64" : "utf-8",
|
||||
content == null ? Base64.getEncoder().encodeToString(file.bytes()) : content,
|
||||
content != null);
|
||||
}
|
||||
|
||||
private void size(long bytes, long max) {
|
||||
if (bytes > max) throw new BusinessException(413, "FILE_TOO_LARGE", "文件或请求超过大小限制");
|
||||
}
|
||||
|
||||
private String expected(Project project, String expectedSha) {
|
||||
String sha = FilePaths.sha(expectedSha);
|
||||
if (!sha.equals(gitea.head(projects.repository(project))))
|
||||
throw BusinessException.conflict("工作区版本已变化,请刷新后重新提交");
|
||||
return sha;
|
||||
}
|
||||
|
||||
public CommitView commit(long userId, String code, CommitInput input) {
|
||||
return projects.write(
|
||||
userId,
|
||||
code,
|
||||
project -> {
|
||||
projects.ready(project);
|
||||
String sha = expected(project, input.expectedCommitSha());
|
||||
GiteaClient.Repository repo = projects.repository(project);
|
||||
List<GiteaClient.Change> changes = new ArrayList<>();
|
||||
Set<String> paths = new HashSet<>();
|
||||
long bytes = 0;
|
||||
for (FileChange item : input.changes()) {
|
||||
String path = FilePaths.file(item.path());
|
||||
if (item.action() == ChangeAction.CREATE_DIRECTORY) path += "/.gitkeep";
|
||||
if (!paths.add(path)) throw BusinessException.badRequest("一次提交不能重复修改同一路径");
|
||||
switch (item.action()) {
|
||||
case CREATE_FILE, CREATE_DIRECTORY -> {
|
||||
String content =
|
||||
item.action() == ChangeAction.CREATE_DIRECTORY
|
||||
? ""
|
||||
: item.content();
|
||||
if (content == null)
|
||||
throw BusinessException.badRequest("新文件必须提供 content");
|
||||
byte[] data = content.getBytes(StandardCharsets.UTF_8);
|
||||
size(data.length, config.getMaxTextBytes());
|
||||
changes.add(new GiteaClient.Change("create", path, null, data));
|
||||
bytes += data.length;
|
||||
}
|
||||
case UPDATE_FILE -> {
|
||||
if (item.content() == null)
|
||||
throw BusinessException.badRequest("修改文件必须提供 content");
|
||||
GiteaClient.StoredFile old = gitea.file(repo, sha, path);
|
||||
if (text(old.bytes()) == null)
|
||||
throw BusinessException.badRequest("该文件不支持在线文本编辑,请通过上传替换");
|
||||
byte[] data = item.content().getBytes(StandardCharsets.UTF_8);
|
||||
size(data.length, config.getMaxTextBytes());
|
||||
changes.add(
|
||||
new GiteaClient.Change(
|
||||
"update", path, old.blobSha(), data));
|
||||
bytes += data.length;
|
||||
}
|
||||
case DELETE_FILE -> {
|
||||
GiteaClient.StoredFile old = gitea.file(repo, sha, path);
|
||||
changes.add(
|
||||
new GiteaClient.Change(
|
||||
"delete", path, old.blobSha(), null));
|
||||
}
|
||||
}
|
||||
}
|
||||
size(bytes, config.getMaxRequestBytes());
|
||||
User user = users.require(userId);
|
||||
CommitView result =
|
||||
gitea.commit(
|
||||
repo,
|
||||
changes,
|
||||
input.message(),
|
||||
user.getNickname(),
|
||||
user.getUserCode());
|
||||
log.info(
|
||||
"文件提交 projectCode={} commitSha={} fileCount={}",
|
||||
code,
|
||||
result.commitSha(),
|
||||
changes.size());
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
public CommitView upload(
|
||||
long userId,
|
||||
String code,
|
||||
String expectedSha,
|
||||
String message,
|
||||
String directory,
|
||||
List<MultipartFile> files,
|
||||
List<String> paths) {
|
||||
if (message == null || message.isBlank() || message.length() > 1000)
|
||||
throw BusinessException.badRequest("提交说明不合法");
|
||||
if (files == null
|
||||
|| files.isEmpty()
|
||||
|| files.size() > 500
|
||||
|| (paths != null && paths.size() != files.size()))
|
||||
throw BusinessException.badRequest("文件和路径数量不合法");
|
||||
String prefix = FilePaths.directory(directory);
|
||||
return projects.write(
|
||||
userId,
|
||||
code,
|
||||
project -> {
|
||||
projects.ready(project);
|
||||
String sha = expected(project, expectedSha);
|
||||
GiteaClient.Repository repo = projects.repository(project);
|
||||
List<GiteaClient.Change> changes = new ArrayList<>();
|
||||
Set<String> unique = new HashSet<>();
|
||||
long bytes = 0;
|
||||
for (int i = 0; i < files.size(); i++) {
|
||||
MultipartFile file = files.get(i);
|
||||
String relative =
|
||||
FilePaths.file(
|
||||
paths == null ? file.getOriginalFilename() : paths.get(i));
|
||||
String path =
|
||||
FilePaths.file(
|
||||
prefix.isEmpty() ? relative : prefix + "/" + relative);
|
||||
if (!unique.add(path)) throw BusinessException.badRequest("上传路径不能重复");
|
||||
size(file.getSize(), config.getMaxFileBytes());
|
||||
bytes += file.getSize();
|
||||
size(bytes, config.getMaxRequestBytes());
|
||||
byte[] data;
|
||||
try {
|
||||
data = file.getBytes();
|
||||
} catch (IOException error) {
|
||||
throw BusinessException.badRequest("读取上传文件失败");
|
||||
}
|
||||
String blob = null;
|
||||
try {
|
||||
blob = gitea.file(repo, sha, path).blobSha();
|
||||
} catch (GiteaFailure missing) {
|
||||
if (missing.status() != 404) throw missing;
|
||||
}
|
||||
changes.add(
|
||||
new GiteaClient.Change(
|
||||
blob == null ? "create" : "update", path, blob, data));
|
||||
}
|
||||
User user = users.require(userId);
|
||||
CommitView result =
|
||||
gitea.commit(
|
||||
repo, changes, message, user.getNickname(), user.getUserCode());
|
||||
log.info(
|
||||
"文件上传 projectCode={} commitSha={} fileCount={}",
|
||||
code,
|
||||
result.commitSha(),
|
||||
changes.size());
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
public PageResponse<HistoryEntry> history(long userId, String code, long page, long size) {
|
||||
ProjectService.pageCheck(page, size);
|
||||
return gitea.history(projects.repository(projects.readyOwner(userId, code)), page, size);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.linkerbot.community.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.bean.entity.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.mapper.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class InteractionService {
|
||||
private static final Logger log = LoggerFactory.getLogger(InteractionService.class);
|
||||
private final ProjectService projects;
|
||||
private final UserService users;
|
||||
private final CommentMapper comments;
|
||||
private final LikeMapper likes;
|
||||
|
||||
public PageResponse<CommentView> list(String code, long page, long size) {
|
||||
ProjectService.pageCheck(page, size);
|
||||
Project project = projects.published(code);
|
||||
Page<ProjectComment> result =
|
||||
comments.selectPage(
|
||||
new Page<>(page, size),
|
||||
new LambdaQueryWrapper<ProjectComment>()
|
||||
.eq(ProjectComment::getProjectId, project.getId())
|
||||
.eq(ProjectComment::getDeleted, false)
|
||||
.orderByDesc(ProjectComment::getCreatedAt)
|
||||
.orderByDesc(ProjectComment::getId));
|
||||
return new PageResponse<>(
|
||||
result.getRecords().stream().map(this::view).toList(),
|
||||
page,
|
||||
size,
|
||||
result.getTotal());
|
||||
}
|
||||
|
||||
private CommentView view(ProjectComment comment) {
|
||||
return new CommentView(
|
||||
comment.getCommentCode(),
|
||||
users.publicView(comment.getUserId()),
|
||||
comment.getContent(),
|
||||
comment.getCreatedAt());
|
||||
}
|
||||
|
||||
public CommentView comment(long userId, String code, CommentInput input) {
|
||||
users.require(userId);
|
||||
Project project = projects.published(code);
|
||||
ProjectComment comment = new ProjectComment();
|
||||
comment.setCommentCode(Codes.next());
|
||||
comment.setProjectId(project.getId());
|
||||
comment.setUserId(userId);
|
||||
comment.setContent(input.content().trim());
|
||||
comment.setDeleted(false);
|
||||
comment.setCreatedAt(ProjectService.now());
|
||||
comment.setUpdatedAt(comment.getCreatedAt());
|
||||
comments.insert(comment);
|
||||
log.info("新增评论 projectCode={} commentCode={}", code, comment.getCommentCode());
|
||||
return view(comment);
|
||||
}
|
||||
|
||||
public void deleteComment(long userId, String code) {
|
||||
int count =
|
||||
comments.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<ProjectComment>()
|
||||
.eq(ProjectComment::getCommentCode, code)
|
||||
.eq(ProjectComment::getUserId, userId)
|
||||
.eq(ProjectComment::getDeleted, false)
|
||||
.set(ProjectComment::getDeleted, true)
|
||||
.set(ProjectComment::getUpdatedAt, ProjectService.now()));
|
||||
if (count == 0) throw BusinessException.notFound();
|
||||
log.info("删除评论 commentCode={}", code);
|
||||
}
|
||||
|
||||
public void like(long userId, String code) {
|
||||
users.require(userId);
|
||||
Project project = projects.published(code);
|
||||
ProjectLike like = new ProjectLike();
|
||||
like.setProjectId(project.getId());
|
||||
like.setUserId(userId);
|
||||
like.setCreatedAt(ProjectService.now());
|
||||
try {
|
||||
likes.insert(like);
|
||||
} catch (DuplicateKeyException duplicate) {
|
||||
return;
|
||||
}
|
||||
log.info("点赞 projectCode={}", code);
|
||||
}
|
||||
|
||||
public void unlike(long userId, String code) {
|
||||
Project project = projects.published(code);
|
||||
likes.delete(
|
||||
new LambdaQueryWrapper<ProjectLike>()
|
||||
.eq(ProjectLike::getProjectId, project.getId())
|
||||
.eq(ProjectLike::getUserId, userId));
|
||||
log.info("取消点赞 projectCode={}", code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.linkerbot.community.service;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@Component
|
||||
public class ProjectLocks {
|
||||
private final ReentrantLock[] locks = new ReentrantLock[128];
|
||||
private final Set<String> uncertain = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public ProjectLocks() {
|
||||
for (int i = 0; i < locks.length; i++) locks[i] = new ReentrantLock();
|
||||
}
|
||||
|
||||
public <T> T write(String code, Supplier<T> action) {
|
||||
return serial(
|
||||
code,
|
||||
() -> {
|
||||
if (uncertain.contains(code))
|
||||
throw new BusinessException(
|
||||
409, "REMOTE_RESULT_UNKNOWN", "上次仓库写入结果待人工核对,暂不能继续写入");
|
||||
return action.get();
|
||||
});
|
||||
}
|
||||
|
||||
public <T> T serial(String code, Supplier<T> action) {
|
||||
ReentrantLock lock = locks[Math.floorMod(code.hashCode(), locks.length)];
|
||||
lock.lock();
|
||||
try {
|
||||
return action.get();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void markUncertain(String code) {
|
||||
uncertain.add(code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package com.linkerbot.community.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.bean.entity.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
import com.linkerbot.community.service.gitea.*;
|
||||
import com.linkerbot.community.service.mapper.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ProjectService {
|
||||
private static final Logger log = LoggerFactory.getLogger(ProjectService.class);
|
||||
private final ProjectMapper projects;
|
||||
private final LikeMapper likes;
|
||||
private final CommentMapper comments;
|
||||
private final UserService users;
|
||||
private final GiteaClient gitea;
|
||||
private final CommunityProperties config;
|
||||
private final ProjectLocks locks;
|
||||
|
||||
public static LocalDateTime now() {
|
||||
return LocalDateTime.now(Clock.systemUTC());
|
||||
}
|
||||
|
||||
public static void pageCheck(long page, long size) {
|
||||
if (page < 1 || page > 100000 || size < 1 || size > 100)
|
||||
throw BusinessException.badRequest("分页参数不合法");
|
||||
}
|
||||
|
||||
public List<TypeView> types() {
|
||||
return config.getTypes().entrySet().stream()
|
||||
.map(e -> new TypeView(e.getKey(), e.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void validateInput(ProjectInput input) {
|
||||
if (!config.getTypes().containsKey(input.projectType()))
|
||||
throw BusinessException.badRequest("项目类型不在可选列表中");
|
||||
}
|
||||
|
||||
public Project owner(long userId, String code) {
|
||||
Project project =
|
||||
projects.selectOne(
|
||||
new LambdaQueryWrapper<Project>()
|
||||
.eq(Project::getProjectCode, code)
|
||||
.eq(Project::getOwnerUserId, userId)
|
||||
.eq(Project::getDeleted, false));
|
||||
if (project == null) throw BusinessException.notFound();
|
||||
return project;
|
||||
}
|
||||
|
||||
public Project readyOwner(long userId, String code) {
|
||||
Project project = owner(userId, code);
|
||||
ready(project);
|
||||
return project;
|
||||
}
|
||||
|
||||
public void ready(Project project) {
|
||||
if (!"READY".equals(project.getRepoStatus()))
|
||||
throw BusinessException.conflict("仓库尚未就绪,请核对项目创建状态");
|
||||
}
|
||||
|
||||
public Project published(String code) {
|
||||
Project project =
|
||||
projects.selectOne(
|
||||
new LambdaQueryWrapper<Project>()
|
||||
.eq(Project::getProjectCode, code)
|
||||
.eq(Project::getDeleted, false)
|
||||
.eq(Project::getRepoStatus, "READY")
|
||||
.eq(Project::getPublishStatus, "PUBLISHED"));
|
||||
if (project == null) throw BusinessException.notFound();
|
||||
return project;
|
||||
}
|
||||
|
||||
public GiteaClient.Repository repository(Project project) {
|
||||
return new GiteaClient.Repository(
|
||||
project.getGiteaRepoId(), project.getGiteaOwner(), project.getGiteaRepoName());
|
||||
}
|
||||
|
||||
public ProjectView view(Project project, Long currentUser) {
|
||||
Project source =
|
||||
project.getSourceProjectId() == null
|
||||
? null
|
||||
: projects.selectById(project.getSourceProjectId());
|
||||
long likeCount =
|
||||
likes.selectCount(
|
||||
new LambdaQueryWrapper<ProjectLike>()
|
||||
.eq(ProjectLike::getProjectId, project.getId()));
|
||||
long commentCount =
|
||||
comments.selectCount(
|
||||
new LambdaQueryWrapper<ProjectComment>()
|
||||
.eq(ProjectComment::getProjectId, project.getId())
|
||||
.eq(ProjectComment::getDeleted, false));
|
||||
boolean liked =
|
||||
currentUser != null
|
||||
&& likes.selectCount(
|
||||
new LambdaQueryWrapper<ProjectLike>()
|
||||
.eq(ProjectLike::getProjectId, project.getId())
|
||||
.eq(ProjectLike::getUserId, currentUser))
|
||||
> 0;
|
||||
return new ProjectView(
|
||||
project.getProjectCode(),
|
||||
project.getName(),
|
||||
project.getDescription(),
|
||||
project.getProjectType(),
|
||||
users.publicView(project.getOwnerUserId()),
|
||||
project.getRepoStatus(),
|
||||
project.getPublishStatus(),
|
||||
project.getPublishedCommitSha(),
|
||||
project.getPublishedAt(),
|
||||
source == null ? null : source.getProjectCode(),
|
||||
project.getSourceCommitSha(),
|
||||
likeCount,
|
||||
commentCount,
|
||||
liked,
|
||||
project.getCreatedAt(),
|
||||
project.getUpdatedAt());
|
||||
}
|
||||
|
||||
public PageResponse<ProjectView> list(
|
||||
Long ownerId, String type, String keyword, long page, long size, Long currentUser) {
|
||||
pageCheck(page, size);
|
||||
LambdaQueryWrapper<Project> query =
|
||||
new LambdaQueryWrapper<Project>().eq(Project::getDeleted, false);
|
||||
if (ownerId == null)
|
||||
query.eq(Project::getRepoStatus, "READY")
|
||||
.eq(Project::getPublishStatus, "PUBLISHED")
|
||||
.orderByDesc(Project::getPublishedAt);
|
||||
else query.eq(Project::getOwnerUserId, ownerId).orderByDesc(Project::getCreatedAt);
|
||||
if (type != null && !type.isBlank()) query.eq(Project::getProjectType, type);
|
||||
if (keyword != null && !keyword.isBlank()) {
|
||||
if (keyword.length() > 200) throw BusinessException.badRequest("关键词过长");
|
||||
query.and(
|
||||
q ->
|
||||
q.like(Project::getName, keyword)
|
||||
.or()
|
||||
.like(Project::getDescription, keyword));
|
||||
}
|
||||
query.orderByDesc(Project::getId);
|
||||
Page<Project> result = projects.selectPage(new Page<>(page, size), query);
|
||||
return new PageResponse<>(
|
||||
result.getRecords().stream().map(p -> view(p, currentUser)).toList(),
|
||||
page,
|
||||
size,
|
||||
result.getTotal());
|
||||
}
|
||||
|
||||
private Project initialize(long userId, ProjectInput input, Project source) {
|
||||
validateInput(input);
|
||||
Project project = new Project();
|
||||
project.setProjectCode(Codes.next());
|
||||
project.setOwnerUserId(userId);
|
||||
project.setName(input.name().trim());
|
||||
project.setDescription(input.description() == null ? "" : input.description());
|
||||
project.setProjectType(input.projectType());
|
||||
project.setGiteaOwner(config.getGitea().getOwner());
|
||||
project.setGiteaRepoName("p_" + project.getProjectCode());
|
||||
project.setRepoStatus("CREATING");
|
||||
project.setPublishStatus("UNPUBLISHED");
|
||||
project.setDeleted(false);
|
||||
project.setCreatedAt(now());
|
||||
project.setUpdatedAt(project.getCreatedAt());
|
||||
if (source != null) {
|
||||
project.setSourceProjectId(source.getId());
|
||||
project.setSourceCommitSha(source.getPublishedCommitSha());
|
||||
}
|
||||
projects.insert(project);
|
||||
return project;
|
||||
}
|
||||
|
||||
public ProjectView create(long userId, ProjectInput input) {
|
||||
users.require(userId);
|
||||
Project project = initialize(userId, input, null);
|
||||
return locks.write(project.getProjectCode(), () -> createRemote(project, null));
|
||||
}
|
||||
|
||||
public ProjectView fork(long userId, String sourceCode, ForkInput input) {
|
||||
User user = users.require(userId);
|
||||
Project source = published(sourceCode);
|
||||
if (!source.getPublishedCommitSha().equals(FilePaths.sha(input.publishedCommitSha())))
|
||||
throw BusinessException.conflict("社区版本已更新,请刷新后 Fork");
|
||||
ProjectInput data =
|
||||
new ProjectInput(input.name(), source.getDescription(), source.getProjectType());
|
||||
Project project = initialize(userId, data, source);
|
||||
return locks.write(
|
||||
project.getProjectCode(),
|
||||
() -> createRemote(project, new ForkContext(source, user)));
|
||||
}
|
||||
|
||||
private record ForkContext(Project source, User user) {}
|
||||
|
||||
private ProjectView createRemote(Project project, ForkContext fork) {
|
||||
try {
|
||||
GiteaClient.Repository repo =
|
||||
gitea.createRepository(project.getGiteaRepoName(), fork == null);
|
||||
project.setGiteaRepoId(repo.id());
|
||||
if (fork != null)
|
||||
copySnapshot(
|
||||
repository(fork.source()),
|
||||
fork.source().getPublishedCommitSha(),
|
||||
repo,
|
||||
fork.user());
|
||||
project.setRepoStatus("READY");
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
log.info("仓库创建完成 projectCode={} fork={}", project.getProjectCode(), fork != null);
|
||||
return view(project, project.getOwnerUserId());
|
||||
} catch (GiteaFailure error) {
|
||||
project.setRepoStatus(error.uncertain() ? "CREATING" : "FAILED");
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
if (error.uncertain()) locks.markUncertain(project.getProjectCode());
|
||||
log.warn(
|
||||
"仓库创建异常 projectCode={} code={} uncertain={}",
|
||||
project.getProjectCode(),
|
||||
error.code(),
|
||||
error.uncertain());
|
||||
throw new BusinessException(
|
||||
error.status(),
|
||||
error.code(),
|
||||
error.getMessage(),
|
||||
Map.of("projectCode", project.getProjectCode()));
|
||||
} catch (BusinessException error) {
|
||||
project.setRepoStatus("FAILED");
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
log.warn("项目初始化拒绝 projectCode={} code={}", project.getProjectCode(), error.code());
|
||||
throw new BusinessException(
|
||||
error.status(),
|
||||
error.code(),
|
||||
error.getMessage(),
|
||||
Map.of("projectCode", project.getProjectCode()));
|
||||
} catch (RuntimeException error) {
|
||||
log.error(
|
||||
"仓库创建或回写异常 projectCode={} type={}",
|
||||
project.getProjectCode(),
|
||||
error.getClass().getSimpleName());
|
||||
throw new BusinessException(
|
||||
500,
|
||||
"PROJECT_INITIALIZATION_ERROR",
|
||||
"项目初始化未完成,请按项目编码人工核对",
|
||||
Map.of("projectCode", project.getProjectCode()));
|
||||
}
|
||||
}
|
||||
|
||||
private void copySnapshot(
|
||||
GiteaClient.Repository source, String sha, GiteaClient.Repository target, User user) {
|
||||
Deque<String> directories = new ArrayDeque<>();
|
||||
directories.add("");
|
||||
List<GiteaClient.Change> batch = new ArrayList<>();
|
||||
long batchBytes = 0;
|
||||
while (!directories.isEmpty()) {
|
||||
for (TreeEntry entry : gitea.tree(source, sha, directories.removeFirst())) {
|
||||
FilePaths.file(entry.path());
|
||||
if (entry.type().equals("dir")) {
|
||||
directories.add(entry.path());
|
||||
continue;
|
||||
}
|
||||
if (!entry.type().equals("file"))
|
||||
throw BusinessException.badRequest("Fork 暂不支持符号链接或子模块");
|
||||
GiteaClient.StoredFile file = gitea.file(source, sha, entry.path());
|
||||
if (!batch.isEmpty()
|
||||
&& (batchBytes + file.bytes().length > config.getMaxRequestBytes()
|
||||
|| batch.size() >= 100)) {
|
||||
gitea.commit(
|
||||
target,
|
||||
batch,
|
||||
"Fork community snapshot",
|
||||
user.getNickname(),
|
||||
user.getUserCode());
|
||||
batch.clear();
|
||||
batchBytes = 0;
|
||||
}
|
||||
batch.add(new GiteaClient.Change("create", file.path(), null, file.bytes()));
|
||||
batchBytes += file.bytes().length;
|
||||
}
|
||||
}
|
||||
if (!batch.isEmpty())
|
||||
gitea.commit(
|
||||
target,
|
||||
batch,
|
||||
"Fork community snapshot",
|
||||
user.getNickname(),
|
||||
user.getUserCode());
|
||||
else if (batchBytes == 0) throw BusinessException.badRequest("不能 Fork 空仓库");
|
||||
}
|
||||
|
||||
public <T> T write(long userId, String code, Function<Project, T> action) {
|
||||
return locks.write(
|
||||
code,
|
||||
() -> {
|
||||
Project project = owner(userId, code);
|
||||
try {
|
||||
return action.apply(project);
|
||||
} catch (GiteaFailure error) {
|
||||
if (error.uncertain()) locks.markUncertain(code);
|
||||
log.warn(
|
||||
"仓库访问异常 projectCode={} code={} uncertain={}",
|
||||
code,
|
||||
error.code(),
|
||||
error.uncertain());
|
||||
throw new BusinessException(
|
||||
error.status(),
|
||||
error.code(),
|
||||
error.getMessage(),
|
||||
Map.of("projectCode", code));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public ProjectView update(long userId, String code, ProjectInput input) {
|
||||
validateInput(input);
|
||||
return metadata(
|
||||
userId,
|
||||
code,
|
||||
project -> {
|
||||
project.setName(input.name().trim());
|
||||
project.setDescription(input.description() == null ? "" : input.description());
|
||||
project.setProjectType(input.projectType());
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
return view(project, userId);
|
||||
});
|
||||
}
|
||||
|
||||
public void delete(long userId, String code) {
|
||||
metadata(
|
||||
userId,
|
||||
code,
|
||||
project -> {
|
||||
project.setDeleted(true);
|
||||
project.setPublishStatus("UNPUBLISHED");
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
log.info("删除项目 projectCode={}", code);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public ProjectView publish(long userId, String code, String expectedSha) {
|
||||
return write(
|
||||
userId,
|
||||
code,
|
||||
project -> {
|
||||
ready(project);
|
||||
String head = gitea.head(repository(project));
|
||||
if (!head.equals(FilePaths.sha(expectedSha)))
|
||||
throw BusinessException.conflict("工作区版本已变化,请刷新后发布");
|
||||
project.setPublishedCommitSha(head);
|
||||
project.setPublishStatus("PUBLISHED");
|
||||
project.setPublishedAt(now());
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
log.info("发布社区 projectCode={} commitSha={}", code, head);
|
||||
return view(project, userId);
|
||||
});
|
||||
}
|
||||
|
||||
public void withdraw(long userId, String code) {
|
||||
metadata(
|
||||
userId,
|
||||
code,
|
||||
project -> {
|
||||
project.setPublishStatus("UNPUBLISHED");
|
||||
project.setUpdatedAt(now());
|
||||
projects.updateById(project);
|
||||
log.info("撤回社区 projectCode={}", code);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private <T> T metadata(long userId, String code, Function<Project, T> action) {
|
||||
return locks.serial(code, () -> action.apply(owner(userId, code)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.linkerbot.community.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.mapper.UserMapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Locale;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
private static final Logger log = LoggerFactory.getLogger(UserService.class);
|
||||
private final UserMapper users;
|
||||
|
||||
public User login(String email) {
|
||||
String normalized = email.trim().toLowerCase(Locale.ROOT);
|
||||
User user = users.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, normalized));
|
||||
if (user == null) {
|
||||
User candidate = new User();
|
||||
candidate.setUserCode(Codes.next());
|
||||
candidate.setEmail(normalized);
|
||||
candidate.setNickname("用户_" + candidate.getUserCode().substring(0, 8));
|
||||
candidate.setStatus("ACTIVE");
|
||||
candidate.setCreatedAt(LocalDateTime.now(Clock.systemUTC()));
|
||||
candidate.setUpdatedAt(candidate.getCreatedAt());
|
||||
try {
|
||||
users.insert(candidate);
|
||||
user = candidate;
|
||||
log.info("创建用户 userCode={}", user.getUserCode());
|
||||
} catch (DuplicateKeyException duplicate) {
|
||||
user =
|
||||
users.selectOne(
|
||||
new LambdaQueryWrapper<User>().eq(User::getEmail, normalized));
|
||||
}
|
||||
}
|
||||
if (user == null || !"ACTIVE".equals(user.getStatus()))
|
||||
throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用");
|
||||
log.info("用户登录 userCode={}", user.getUserCode());
|
||||
return user;
|
||||
}
|
||||
|
||||
public User require(long id) {
|
||||
User user = users.selectById(id);
|
||||
if (user == null || !"ACTIVE".equals(user.getStatus()))
|
||||
throw new BusinessException(401, "UNAUTHORIZED", "请重新登录");
|
||||
return user;
|
||||
}
|
||||
|
||||
public UserView view(User user) {
|
||||
return new UserView(user.getUserCode(), user.getNickname(), user.getEmail());
|
||||
}
|
||||
|
||||
public PublicUser publicView(long id) {
|
||||
User user = users.selectById(id);
|
||||
return user == null
|
||||
? new PublicUser(null, "已删除用户")
|
||||
: new PublicUser(user.getUserCode(), user.getNickname());
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.linkerbot.community.service.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "community")
|
||||
public class CommunityProperties {
|
||||
private Map<String, String> types = defaultTypes();
|
||||
private long maxTextBytes = 1024 * 1024;
|
||||
private long maxFileBytes = 10 * 1024 * 1024;
|
||||
private long maxRequestBytes = 50 * 1024 * 1024;
|
||||
private Duration captchaTtl = Duration.ofMinutes(2);
|
||||
private Duration tokenTtl = Duration.ofHours(24);
|
||||
private Gitea gitea = new Gitea();
|
||||
|
||||
private static Map<String, String> defaultTypes() {
|
||||
Map<String, String> types = new LinkedHashMap<>();
|
||||
types.put("GENERAL", "通用");
|
||||
types.put("HUMANOID", "人形");
|
||||
types.put("QUADRUPED", "四足");
|
||||
types.put("WHEELED", "轮式");
|
||||
return types;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Gitea {
|
||||
private String baseUrl = "http://localhost:3000";
|
||||
private String owner = "community";
|
||||
private String token = "";
|
||||
private Duration connectTimeout = Duration.ofSeconds(5);
|
||||
private Duration requestTimeout = Duration.ofSeconds(30);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.linkerbot.community.service.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MybatisConfiguration {
|
||||
@Bean
|
||||
public MybatisPlusInterceptor paginationInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.linkerbot.community.service.gitea;
|
||||
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.common.PageResponse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface GiteaClient {
|
||||
record Repository(long id, String owner, String name) {}
|
||||
|
||||
record StoredFile(String path, String blobSha, byte[] bytes) {}
|
||||
|
||||
record Change(String operation, String path, String blobSha, byte[] bytes) {}
|
||||
|
||||
Repository createRepository(String name, boolean initialize);
|
||||
|
||||
String head(Repository repository);
|
||||
|
||||
List<TreeEntry> tree(Repository repository, String sha, String path);
|
||||
|
||||
StoredFile file(Repository repository, String sha, String path);
|
||||
|
||||
CommitView commit(
|
||||
Repository repository,
|
||||
List<Change> changes,
|
||||
String message,
|
||||
String authorName,
|
||||
String authorCode);
|
||||
|
||||
PageResponse<HistoryEntry> history(Repository repository, long page, long size);
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.linkerbot.community.service.gitea;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
|
||||
public class GiteaFailure extends BusinessException {
|
||||
private final boolean uncertain;
|
||||
|
||||
public GiteaFailure(int status, String code, String message, boolean uncertain) {
|
||||
super(status, code, message);
|
||||
this.uncertain = uncertain;
|
||||
}
|
||||
|
||||
public boolean uncertain() {
|
||||
return uncertain;
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package com.linkerbot.community.service.gitea;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
import com.linkerbot.community.common.FilePaths;
|
||||
import com.linkerbot.community.common.PageResponse;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
@Component
|
||||
public class RestGiteaClient implements GiteaClient {
|
||||
private final CommunityProperties properties;
|
||||
private final ObjectMapper json;
|
||||
private final HttpClient http;
|
||||
|
||||
public RestGiteaClient(CommunityProperties properties, ObjectMapper json) {
|
||||
this.properties = properties;
|
||||
this.json = json;
|
||||
this.http =
|
||||
HttpClient.newBuilder()
|
||||
.connectTimeout(properties.getGitea().getConnectTimeout())
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String encode(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
}
|
||||
|
||||
private String repoPath(Repository repo) {
|
||||
return "/repos/" + encode(repo.owner()) + "/" + encode(repo.name());
|
||||
}
|
||||
|
||||
private String filePath(String path) {
|
||||
return Arrays.stream(path.split("/"))
|
||||
.map(RestGiteaClient::encode)
|
||||
.reduce((a, b) -> a + "/" + b)
|
||||
.orElse("");
|
||||
}
|
||||
|
||||
private HttpResponse<byte[]> request(String method, String path, Object body) {
|
||||
if (properties.getGitea().getToken().isBlank())
|
||||
throw new GiteaFailure(503, "GITEA_NOT_CONFIGURED", "请配置 Gitea Token", false);
|
||||
try {
|
||||
String base = properties.getGitea().getBaseUrl().replaceAll("/+$", "");
|
||||
HttpRequest.Builder builder =
|
||||
HttpRequest.newBuilder(URI.create(base + "/api/v1" + path))
|
||||
.timeout(properties.getGitea().getRequestTimeout())
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", "token " + properties.getGitea().getToken());
|
||||
if (body == null) builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
else
|
||||
builder.header("Content-Type", "application/json")
|
||||
.method(
|
||||
method,
|
||||
HttpRequest.BodyPublishers.ofByteArray(
|
||||
json.writeValueAsBytes(body)));
|
||||
HttpResponse<byte[]> response =
|
||||
http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
int status = response.statusCode();
|
||||
if (status < 200 || status >= 300) {
|
||||
if (status == 404) throw new GiteaFailure(404, "NOT_FOUND", "仓库文件或版本不存在", false);
|
||||
if (status == 409 || status == 422)
|
||||
throw new GiteaFailure(409, "GITEA_CONFLICT", "仓库内容冲突,请刷新后重试", false);
|
||||
throw new GiteaFailure(
|
||||
502,
|
||||
"GITEA_ERROR",
|
||||
"仓库服务返回异常,请通过 requestId 排查",
|
||||
!method.equals("GET") && status >= 500);
|
||||
}
|
||||
return response;
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new GiteaFailure(
|
||||
504, "REMOTE_RESULT_UNKNOWN", "仓库调用被中断,写入结果需核对", !method.equals("GET"));
|
||||
} catch (IOException error) {
|
||||
throw new GiteaFailure(
|
||||
504, "REMOTE_RESULT_UNKNOWN", "仓库连接异常或超时,写入结果需核对", !method.equals("GET"));
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode parse(byte[] bytes, boolean writing) {
|
||||
try {
|
||||
return json.readTree(bytes);
|
||||
} catch (IOException error) {
|
||||
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库响应格式异常", writing);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Repository createRepository(String name, boolean initialize) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("name", name);
|
||||
body.put("private", true);
|
||||
body.put("auto_init", initialize);
|
||||
body.put("default_branch", "main");
|
||||
if (initialize) body.put("readme", "Default");
|
||||
String owner = properties.getGitea().getOwner();
|
||||
JsonNode data =
|
||||
parse(request("POST", "/orgs/" + encode(owner) + "/repos", body).body(), true);
|
||||
if (data.path("id").asLong() <= 0 || !data.path("private").asBoolean())
|
||||
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库创建结果异常,需人工核对", true);
|
||||
return new Repository(data.path("id").asLong(), owner, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String head(Repository repo) {
|
||||
JsonNode branch =
|
||||
parse(request("GET", repoPath(repo) + "/branches/main", null).body(), false);
|
||||
return FilePaths.sha(branch.path("commit").path("id").asText());
|
||||
}
|
||||
|
||||
private JsonNode contents(Repository repo, String sha, String path) {
|
||||
String suffix = path.isEmpty() ? "" : "/" + filePath(path);
|
||||
return parse(
|
||||
request(
|
||||
"GET",
|
||||
repoPath(repo)
|
||||
+ "/contents"
|
||||
+ suffix
|
||||
+ "?ref="
|
||||
+ FilePaths.sha(sha),
|
||||
null)
|
||||
.body(),
|
||||
false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TreeEntry> tree(Repository repo, String sha, String path) {
|
||||
JsonNode nodes = contents(repo, sha, FilePaths.directory(path));
|
||||
if (!nodes.isArray()) throw BusinessException.badRequest("路径不是目录");
|
||||
List<TreeEntry> result = new ArrayList<>();
|
||||
for (JsonNode node : nodes)
|
||||
result.add(
|
||||
new TreeEntry(
|
||||
node.path("path").asText(),
|
||||
node.path("name").asText(),
|
||||
node.path("type").asText(),
|
||||
node.path("size").asLong(),
|
||||
node.path("sha").asText()));
|
||||
result.sort(
|
||||
Comparator.comparing((TreeEntry entry) -> !entry.type().equals("dir"))
|
||||
.thenComparing(TreeEntry::name));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StoredFile file(Repository repo, String sha, String path) {
|
||||
FilePaths.file(path);
|
||||
JsonNode node = contents(repo, sha, path);
|
||||
if (!node.isObject() || !node.path("type").asText().equals("file"))
|
||||
throw BusinessException.badRequest("仅支持普通文件,不支持符号链接或子模块");
|
||||
if (node.path("size").asLong() > properties.getMaxFileBytes())
|
||||
throw new BusinessException(413, "FILE_TOO_LARGE", "文件超过读取限制");
|
||||
byte[] bytes;
|
||||
try {
|
||||
if (node.path("encoding").asText().equals("base64") && node.hasNonNull("content"))
|
||||
bytes = Base64.getMimeDecoder().decode(node.path("content").asText());
|
||||
else
|
||||
bytes =
|
||||
request(
|
||||
"GET",
|
||||
repoPath(repo) + "/raw/" + filePath(path) + "?ref=" + sha,
|
||||
null)
|
||||
.body();
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库文件编码异常", false);
|
||||
}
|
||||
if (bytes.length > properties.getMaxFileBytes())
|
||||
throw new BusinessException(413, "FILE_TOO_LARGE", "文件超过读取限制");
|
||||
return new StoredFile(path, node.path("sha").asText(), bytes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommitView commit(
|
||||
Repository repo,
|
||||
List<Change> changes,
|
||||
String message,
|
||||
String authorName,
|
||||
String authorCode) {
|
||||
List<Map<String, Object>> files = new ArrayList<>();
|
||||
for (Change change : changes) {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("operation", change.operation());
|
||||
item.put("path", FilePaths.file(change.path()));
|
||||
if (change.blobSha() != null) item.put("sha", change.blobSha());
|
||||
if (!change.operation().equals("delete"))
|
||||
item.put("content", Base64.getEncoder().encodeToString(change.bytes()));
|
||||
files.add(item);
|
||||
}
|
||||
Map<String, Object> body =
|
||||
Map.of(
|
||||
"branch",
|
||||
"main",
|
||||
"files",
|
||||
files,
|
||||
"message",
|
||||
message,
|
||||
"author",
|
||||
Map.of(
|
||||
"name",
|
||||
authorName,
|
||||
"email",
|
||||
authorCode + "@users.community.invalid"));
|
||||
JsonNode result = parse(request("POST", repoPath(repo) + "/contents", body).body(), true);
|
||||
String sha = result.path("commit").path("sha").asText();
|
||||
if (sha.isBlank())
|
||||
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库未返回提交版本,需人工核对", true);
|
||||
return new CommitView(FilePaths.sha(sha), message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResponse<HistoryEntry> history(Repository repo, long page, long size) {
|
||||
HttpResponse<byte[]> response =
|
||||
request(
|
||||
"GET",
|
||||
repoPath(repo) + "/commits?sha=main&page=" + page + "&limit=" + size,
|
||||
null);
|
||||
JsonNode data = parse(response.body(), false);
|
||||
List<HistoryEntry> items = new ArrayList<>();
|
||||
for (JsonNode node : data) {
|
||||
JsonNode commit = node.path("commit");
|
||||
items.add(
|
||||
new HistoryEntry(
|
||||
node.path("sha").asText(),
|
||||
commit.path("message").asText(),
|
||||
commit.path("author").path("name").asText(),
|
||||
commit.path("author").path("date").asText()));
|
||||
}
|
||||
long total =
|
||||
response.headers()
|
||||
.firstValue("X-Total-Count")
|
||||
.map(Long::parseLong)
|
||||
.orElse((long) items.size());
|
||||
return new PageResponse<>(items, page, size, total);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.linkerbot.community.service.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.community.bean.entity.ProjectComment;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface CommentMapper extends BaseMapper<ProjectComment> {}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.linkerbot.community.service.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.community.bean.entity.ProjectLike;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LikeMapper extends BaseMapper<ProjectLike> {}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.linkerbot.community.service.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.community.bean.entity.Project;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface ProjectMapper extends BaseMapper<Project> {}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.linkerbot.community.service.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface UserMapper extends BaseMapper<User> {}
|
||||
+965
@@ -0,0 +1,965 @@
|
||||
# Community 前端接口对接文档
|
||||
|
||||
供社区列表、项目详情、登录、我的工作区和在线文件编辑页面使用。前端通过 Community 后端完成所有业务操作;登录 Token 是平台 Token,前端不连接 Gitea、不持有 Gitea 凭据。
|
||||
|
||||
当前支持项目、文件、目录、提交、手动发布、快照 Fork、评论和点赞。项目发布后,后续提交只更新工作区,需要再次调用发布接口才更新社区代码。没有服务端草稿保存、AI 检索、独立工作区实体或项目类型表。
|
||||
|
||||
## 阅读导航
|
||||
|
||||
- [接入约定](#接入约定)
|
||||
- [接口总览](#接口总览)
|
||||
- [响应数据结构](#响应数据结构)
|
||||
- [登录和用户](#登录和用户)
|
||||
- [类型与项目列表](#类型与项目列表)
|
||||
- [我的项目管理](#我的项目管理)
|
||||
- [目录和文件读取](#目录和文件读取)
|
||||
- [文件编辑与上传提交](#文件编辑与上传提交)
|
||||
- [社区发布和撤回](#社区发布和撤回)
|
||||
- [社区详情和 Fork](#社区详情和-fork)
|
||||
- [评论和点赞](#评论和点赞)
|
||||
- [错误码与前端处理](#错误码与前端处理)
|
||||
- [页面调用顺序](#页面调用顺序)
|
||||
- [前端请求示例](#前端请求示例)
|
||||
- [后端人工核对](#后端人工核对)
|
||||
|
||||
## 接入约定
|
||||
|
||||
### 地址和请求头
|
||||
|
||||
本机默认后端地址为 `http://localhost:8993`,接口前缀为 `/api`。实际端口可由 `SERVER_PORT` 或 `PORT` 覆盖,部署环境地址由后端提供。
|
||||
|
||||
| 项目 | 约定 |
|
||||
| --- | --- |
|
||||
| JSON 请求 | `Content-Type: application/json` |
|
||||
| 登录凭据 | `Authorization: Bearer <平台 token>`,注意 `Bearer` 的大小写和空格 |
|
||||
| 上传 | `multipart/form-data`,浏览器使用 FormData,不手动设置 Content-Type |
|
||||
| 业务标识 | 使用 `projectCode`、`commentCode`、`userCode`,不使用数据库 ID |
|
||||
| 接口调试 | `/swagger-ui.html` |
|
||||
| OpenAPI | `/v3/api-docs` |
|
||||
|
||||
当前后端没有配置跨域白名单。开发时通过前端开发服务器代理 `/api`,部署时通过同域反向代理访问;仅允许 OPTIONS 请求不代表已经支持浏览器跨域访问。
|
||||
|
||||
### 统一响应
|
||||
|
||||
除成功的文件下载外,响应为以下 JSON 结构。所有成功接口使用 HTTP 200,创建、删除、退出登录也不返回 201 或 204。
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "OK",
|
||||
"message": "成功",
|
||||
"data": null,
|
||||
"requestId": "44444444444444444444444444444444"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| code | string | 成功为 `OK`,失败为业务错误码 |
|
||||
| message | string | 可用于提示用户,不要通过中文 message 判断错误类型 |
|
||||
| data | 对象、数组或 null | 成功数据;失败通常为 null,部分仓库错误包含 projectCode |
|
||||
| requestId | string | 本次请求的排查标识,与响应头 `X-Request-Id` 一致 |
|
||||
|
||||
下面标为“data 示例”的代码块只展示 `data`,实际响应仍有上面的包装。示例业务编码和 SHA 均为虚构,调用时必须使用接口返回的真实值。
|
||||
|
||||
分页接口的 data 为:
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [],
|
||||
"page": 1,
|
||||
"size": 20,
|
||||
"total": 0
|
||||
}
|
||||
```
|
||||
|
||||
`page` 从 1 开始,范围为 1~100000;`size` 默认 20,范围为 1~100。`total` 为数字,不返回额外的 `pages` 字段。空列表是 `items: []`。
|
||||
|
||||
### 时间和版本
|
||||
|
||||
项目和评论的时间字段按 UTC 保存,JSON 格式为 `2026-10-13T08:30:00`,可能带小数秒,**没有时区后缀**。前端解析这些字段时应按 UTC 处理,再转换成用户时区;不要直接当成本地时间。历史提交的 `authorDate` 来自仓库服务,可带 `Z` 或时区偏移。
|
||||
|
||||
Git SHA 使用完整的 40 或 64 位十六进制字符串,不使用缩写。几个版本字段的用途不同:
|
||||
|
||||
| 字段 | 来源 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| commitSha | 目录、文件、提交结果、历史提交 | 读取指定版本;提交结果中的值是新版本 |
|
||||
| expectedCommitSha | 提交请求 | 编辑或上传所基于的工作区版本,防止覆盖其他提交 |
|
||||
| publishedCommitSha | 项目详情 | 社区当前发布版本;Fork 时原样提交此值 |
|
||||
| blobSha | 文件或目录条目 | 文件或目录对应的 Git 对象标识,前端不用它提交文件 |
|
||||
|
||||
项目详情不包含工作区当前 main 的 SHA。进入编辑器、提交或发布前,从工作区目录或文件接口获取 `commitSha`。
|
||||
|
||||
## 接口总览
|
||||
|
||||
“可选登录”表示匿名也能访问;带有效 Token 时项目响应可返回当前用户的 `liked` 状态。公开接口携带已失效的 Bearer Token 仍会返回 401。
|
||||
|
||||
| 方法 | 路径 | 登录 | 成功 data |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/api/auth/captcha` | 否 | Captcha |
|
||||
| POST | `/api/auth/login` | 否 | Login |
|
||||
| POST | `/api/auth/logout` | 是 | null |
|
||||
| GET | `/api/users/me` | 是 | User |
|
||||
| GET | `/api/project-types` | 否 | ProjectType[] |
|
||||
| GET | `/api/workspace/projects` | 是 | PageResult<Project> |
|
||||
| POST | `/api/workspace/projects` | 是 | Project |
|
||||
| GET | `/api/workspace/projects/{projectCode}` | 是 | Project |
|
||||
| PATCH | `/api/workspace/projects/{projectCode}` | 是 | Project |
|
||||
| DELETE | `/api/workspace/projects/{projectCode}` | 是 | null |
|
||||
| GET | `/api/workspace/projects/{projectCode}/tree` | 是 | Tree |
|
||||
| GET | `/api/workspace/projects/{projectCode}/files` | 是 | ProjectFile 或下载二进制 |
|
||||
| POST | `/api/workspace/projects/{projectCode}/commits` | 是 | Commit |
|
||||
| GET | `/api/workspace/projects/{projectCode}/commits` | 是 | PageResult<HistoryEntry> |
|
||||
| POST | `/api/workspace/projects/{projectCode}/uploads/commit` | 是 | Commit |
|
||||
| PUT | `/api/workspace/projects/{projectCode}/publication` | 是 | Project |
|
||||
| DELETE | `/api/workspace/projects/{projectCode}/publication` | 是 | null |
|
||||
| GET | `/api/community/projects` | 可选 | PageResult<Project> |
|
||||
| GET | `/api/community/projects/{projectCode}` | 可选 | Project |
|
||||
| GET | `/api/community/projects/{projectCode}/tree` | 可选 | Tree |
|
||||
| GET | `/api/community/projects/{projectCode}/files` | 可选 | ProjectFile 或下载二进制 |
|
||||
| POST | `/api/community/projects/{projectCode}/forks` | 是 | Project |
|
||||
| GET | `/api/community/projects/{projectCode}/comments` | 可选 | PageResult<Comment> |
|
||||
| POST | `/api/community/projects/{projectCode}/comments` | 是 | Comment |
|
||||
| DELETE | `/api/comments/{commentCode}` | 是 | null |
|
||||
| PUT | `/api/community/projects/{projectCode}/like` | 是 | null |
|
||||
| DELETE | `/api/community/projects/{projectCode}/like` | 是 | null |
|
||||
|
||||
## 响应数据结构
|
||||
|
||||
以下 TypeScript 类型与当前 JSON 字段对应。项目列表、工作区详情、社区详情、创建、修改、发布和 Fork 共用 Project 结构。
|
||||
|
||||
```typescript
|
||||
/** 无时区后缀,按 UTC 解释。 */
|
||||
export type UtcDateTime = string;
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
code: string;
|
||||
message: string;
|
||||
data: T | null;
|
||||
requestId: string;
|
||||
}
|
||||
|
||||
export interface PageResult<T> {
|
||||
items: T[];
|
||||
page: number;
|
||||
size: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface PublicUser {
|
||||
userCode: string | null; // 用户记录不可用时可能为 null
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
userCode: string;
|
||||
nickname: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface Captcha {
|
||||
captchaCode: string;
|
||||
image: string; // PNG data URL,可直接作为 img 的 src
|
||||
expiresIn: number; // 秒
|
||||
}
|
||||
|
||||
export interface Login {
|
||||
token: string;
|
||||
tokenType: 'Bearer';
|
||||
expiresIn: number; // 秒
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface ProjectType {
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
projectCode: string;
|
||||
name: string;
|
||||
description: string;
|
||||
projectType: string;
|
||||
owner: PublicUser;
|
||||
repoStatus: 'CREATING' | 'READY' | 'FAILED';
|
||||
publishStatus: 'UNPUBLISHED' | 'PUBLISHED';
|
||||
publishedCommitSha: string | null;
|
||||
publishedAt: UtcDateTime | null;
|
||||
sourceProjectCode: string | null;
|
||||
sourceCommitSha: string | null;
|
||||
likeCount: number;
|
||||
commentCount: number;
|
||||
liked: boolean;
|
||||
createdAt: UtcDateTime;
|
||||
updatedAt: UtcDateTime;
|
||||
}
|
||||
|
||||
export interface TreeEntry {
|
||||
path: string; // 从仓库根目录开始的完整相对路径
|
||||
name: string;
|
||||
type: string; // 普通目录为 dir,普通文件为 file
|
||||
size: number; // 字节
|
||||
blobSha: string;
|
||||
}
|
||||
|
||||
export interface Tree {
|
||||
commitSha: string;
|
||||
path: string; // 根目录为 ""
|
||||
entries: TreeEntry[]; // 当前目录的直接子项
|
||||
}
|
||||
|
||||
export interface ProjectFile {
|
||||
commitSha: string;
|
||||
path: string;
|
||||
blobSha: string;
|
||||
size: number; // 字节
|
||||
encoding: 'utf-8' | 'base64';
|
||||
content: string;
|
||||
editable: boolean;
|
||||
}
|
||||
|
||||
export interface Commit {
|
||||
commitSha: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
commitSha: string;
|
||||
message: string;
|
||||
authorName: string;
|
||||
authorDate: string; // 仓库服务返回的日期字符串
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
commentCode: string;
|
||||
author: PublicUser;
|
||||
content: string;
|
||||
createdAt: UtcDateTime;
|
||||
}
|
||||
```
|
||||
|
||||
### 项目示例与状态含义
|
||||
|
||||
已发布项目的 data 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectCode": "22222222222222222222222222222222",
|
||||
"name": "机器人示例项目",
|
||||
"description": "模型、配置和说明文件",
|
||||
"projectType": "GENERAL",
|
||||
"owner": {
|
||||
"userCode": "11111111111111111111111111111111",
|
||||
"nickname": "用户_11111111"
|
||||
},
|
||||
"repoStatus": "READY",
|
||||
"publishStatus": "PUBLISHED",
|
||||
"publishedCommitSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"publishedAt": "2026-10-13T08:30:00",
|
||||
"sourceProjectCode": null,
|
||||
"sourceCommitSha": null,
|
||||
"likeCount": 3,
|
||||
"commentCount": 2,
|
||||
"liked": false,
|
||||
"createdAt": "2026-10-13T08:00:00",
|
||||
"updatedAt": "2026-10-13T08:30:00"
|
||||
}
|
||||
```
|
||||
|
||||
| 状态或字段 | 前端使用方式 |
|
||||
| --- | --- |
|
||||
| repoStatus = CREATING | 仓库初始化未完成,可能需要人工核对;关闭文件读取、提交和发布入口 |
|
||||
| repoStatus = READY | 仓库已就绪,可进入文件操作;仍需处理版本冲突或写入待核对错误 |
|
||||
| repoStatus = FAILED | 初始化失败,显示失败状态;仍可修改项目信息或删除项目 |
|
||||
| publishStatus = UNPUBLISHED | 当前不在社区展示;这是私有项目状态,不是草稿 |
|
||||
| publishStatus = PUBLISHED | 当前在社区展示 |
|
||||
| publishedCommitSha / publishedAt | 撤回后可能仍保留上一次发布值,是否公开必须判断 publishStatus |
|
||||
| sourceProjectCode / sourceCommitSha | Fork 来源及复制的源版本;普通新项目为 null |
|
||||
| liked | 当前请求用户是否点赞,匿名访问为 false |
|
||||
|
||||
工作区归属由 `owner.userCode` 判断,不存在 `workspaceCode`。`updatedAt` 不代表仓库最新提交时间。来源项目撤回或删除后,sourceProjectCode 仍可能存在,访问该来源的社区详情会返回 404。
|
||||
|
||||
## 登录和用户
|
||||
|
||||
### 获取图片验证码
|
||||
|
||||
`GET /api/auth/captcha`,无需登录,无参数。
|
||||
|
||||
data 示例中 image 仅展示格式前缀,实际值为完整图片:
|
||||
|
||||
```json
|
||||
{
|
||||
"captchaCode": "55555555555555555555555555555555",
|
||||
"image": "data:image/png;base64,...",
|
||||
"expiresIn": 120
|
||||
}
|
||||
```
|
||||
|
||||
将 image 作为图片 src,将 captchaCode 与用户输入答案一起提交。有效期默认 120 秒,以接口返回值为准。验证码只使用一次,答案错误也会消耗验证码;失败后重新获取图片。答案校验忽略首尾空格和大小写。
|
||||
|
||||
### 邮箱登录
|
||||
|
||||
`POST /api/auth/login`,无需登录。
|
||||
|
||||
| 请求字段 | 必填 | 约束 |
|
||||
| --- | --- | --- |
|
||||
| email | 是 | 合法邮箱,最多 254 字符,前端提交前去掉首尾空格 |
|
||||
| captchaCode | 是 | 验证码接口返回的标识 |
|
||||
| captchaAnswer | 是 | 用户输入的图片验证码 |
|
||||
|
||||
请求:
|
||||
|
||||
```json
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"captchaCode": "55555555555555555555555555555555",
|
||||
"captchaAnswer": "ABCDE"
|
||||
}
|
||||
```
|
||||
|
||||
响应示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "OK",
|
||||
"message": "成功",
|
||||
"data": {
|
||||
"token": "example-platform-token",
|
||||
"tokenType": "Bearer",
|
||||
"expiresIn": 86400,
|
||||
"user": {
|
||||
"userCode": "11111111111111111111111111111111",
|
||||
"nickname": "用户_11111111",
|
||||
"email": "user@example.com"
|
||||
}
|
||||
},
|
||||
"requestId": "44444444444444444444444444444444"
|
||||
}
|
||||
```
|
||||
|
||||
首次登录自动创建用户,邮箱统一转成小写。当前只验证邮箱格式与图片验证码,不发送邮件、不使用密码,也不验证邮箱归属。Token 有效期默认 24 小时,以 expiresIn 为准,不是 JWT,没有刷新 Token 接口;服务重启后需要重新登录。
|
||||
|
||||
### 当前用户和退出登录
|
||||
|
||||
`GET /api/users/me`,需要登录,data 为 User;只有本人用户接口和登录响应包含邮箱,公开作者信息不包含邮箱。
|
||||
|
||||
`POST /api/auth/logout`,需要登录,无请求体,成功 data 为 null。前端清除本地登录状态。已失效 Token 调用退出接口会返回 401,同样可以清除本地登录状态。
|
||||
|
||||
## 类型与项目列表
|
||||
|
||||
### 可选项目类型
|
||||
|
||||
`GET /api/project-types`,无需登录,无参数,data 为 ProjectType[]:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "code": "GENERAL", "name": "通用" },
|
||||
{ "code": "HUMANOID", "name": "人形" },
|
||||
{ "code": "QUADRUPED", "name": "四足" },
|
||||
{ "code": "WHEELED", "name": "轮式" }
|
||||
]
|
||||
```
|
||||
|
||||
左侧类型导航和创建项目下拉框使用这个接口,不在前端写死类型码。“全部”筛选不传 type。当前内置 GENERAL(通用)、HUMANOID(人形)、QUADRUPED(四足)、WHEELED(轮式),创建或修改项目时通过 projectType 提交对应 code,列表筛选时通过 type 提交对应 code。
|
||||
|
||||
### 我的项目列表和社区项目列表
|
||||
|
||||
- `GET /api/workspace/projects`:需要登录,返回本人所有未删除项目,包括 CREATING、FAILED 项目。
|
||||
- `GET /api/community/projects`:可选登录,仅返回 READY 且 PUBLISHED 的项目。
|
||||
|
||||
两者查询参数相同:
|
||||
|
||||
| 参数 | 必填 | 默认 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| page | 否 | 1 | 页码 |
|
||||
| size | 否 | 20 | 每页数量 |
|
||||
| type | 否 | 无 | 项目类型 code;注意查询字段叫 type,不是 projectType |
|
||||
| keyword | 否 | 无 | 名称或描述的模糊查询,最多 200 字符;空白值不筛选 |
|
||||
|
||||
请求示例:`GET /api/community/projects?page=1&size=20&type=GENERAL&keyword=机器人`。使用 URLSearchParams 编码中文等查询值。
|
||||
|
||||
成功 data 为 PageResult<Project>。工作区按创建时间倒序,社区按最近发布时间倒序;不支持客户端指定排序。更换类型或关键词时,把 page 重置为 1。
|
||||
|
||||
## 我的项目管理
|
||||
|
||||
以下接口需要登录,且只能操作当前用户的项目。项目不存在、已删除或属于其他用户,均返回 404。
|
||||
|
||||
### 创建项目
|
||||
|
||||
`POST /api/workspace/projects`。
|
||||
|
||||
| 请求字段 | 必填 | 约束 |
|
||||
| --- | --- | --- |
|
||||
| name | 是 | 非空,最多 100 字符,保存时去掉首尾空格 |
|
||||
| description | 否 | 最多 2000 字符,省略或 null 时保存为空字符串 |
|
||||
| projectType | 是 | 类型接口返回的 code,必须精确匹配,最多 64 字符 |
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "机器人示例项目",
|
||||
"description": "模型、配置和说明文件",
|
||||
"projectType": "GENERAL"
|
||||
}
|
||||
```
|
||||
|
||||
成功 data 为 Project,状态为 READY、UNPUBLISHED。后端已创建私有仓库、main 分支和 README.md。使用返回的 projectCode 进入工作区详情,然后读取根目录获取当前 commitSha。
|
||||
|
||||
创建是同步请求,没有任务编号、202 响应或操作进度查询接口。请求失败可能已经留下项目记录;先查看错误 data.projectCode 和工作区列表,不要自动重发创建请求。
|
||||
|
||||
### 项目详情
|
||||
|
||||
`GET /api/workspace/projects/{projectCode}`,无额外参数,data 为 Project。
|
||||
|
||||
### 修改项目信息
|
||||
|
||||
`PATCH /api/workspace/projects/{projectCode}`。请求字段与创建项目相同,data 为更新后的 Project。
|
||||
|
||||
虽然方法为 PATCH,当前接口要求同时提交 name、projectType;description 省略或 null 会清空描述。前端编辑表单应提交完整的三个字段。
|
||||
|
||||
已发布项目的名称、描述、类型会直接更新社区展示,不生成文件 Commit。
|
||||
|
||||
### 删除项目
|
||||
|
||||
`DELETE /api/workspace/projects/{projectCode}`,无请求体,成功 data 为 null。
|
||||
|
||||
项目逻辑删除并从社区撤回,已有独立 Fork 不受影响。再次操作已删除项目返回 404。
|
||||
|
||||
## 目录和文件读取
|
||||
|
||||
### 工作区目录
|
||||
|
||||
`GET /api/workspace/projects/{projectCode}/tree`,需要登录。
|
||||
|
||||
| 参数 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| path | 否 | 目录相对路径,省略或空字符串表示根目录 |
|
||||
| commitSha | 否 | 省略时读取当前 main;传入时读取该项目指定提交 |
|
||||
|
||||
data 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"path": "",
|
||||
"entries": [
|
||||
{
|
||||
"path": "models",
|
||||
"name": "models",
|
||||
"type": "dir",
|
||||
"size": 0,
|
||||
"blobSha": "cccccccccccccccccccccccccccccccccccccccc"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"name": "README.md",
|
||||
"type": "file",
|
||||
"size": 5,
|
||||
"blobSha": "dddddddddddddddddddddddddddddddddddddddd"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
entries 仅包含当前目录的直接子项,目录在前,名称升序。展开子目录时传条目的完整 path。需要一致的历史文件视图时,目录和文件读取都使用同一个 commitSha。
|
||||
|
||||
### 工作区文件
|
||||
|
||||
`GET /api/workspace/projects/{projectCode}/files`,需要登录。
|
||||
|
||||
| 参数 | 必填 | 默认 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| path | 是 | 无 | 普通文件的相对路径 |
|
||||
| commitSha | 否 | 当前 main | 指定历史提交 |
|
||||
| download | 否 | false | true 返回文件附件 |
|
||||
|
||||
文本文件 data 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"path": "README.md",
|
||||
"blobSha": "dddddddddddddddddddddddddddddddddddddddd",
|
||||
"size": 5,
|
||||
"encoding": "utf-8",
|
||||
"content": "hello",
|
||||
"editable": true
|
||||
}
|
||||
```
|
||||
|
||||
二进制文件 data 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"path": "models/data.bin",
|
||||
"blobSha": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
|
||||
"size": 3,
|
||||
"encoding": "base64",
|
||||
"content": "AAEC",
|
||||
"editable": false
|
||||
}
|
||||
```
|
||||
|
||||
只有 UTF-8、没有 NUL 字节且不超过文本编辑限制的文件返回 editable=true。二进制文件或超过编辑限制的文本返回 base64,不能直接把 base64 放进编辑器提交;使用上传替换。文件和下载均受单文件读取上限限制。
|
||||
|
||||
`download=true` 成功返回 `application/octet-stream`,带 `Content-Disposition: attachment`,不套 JSON。工作区下载需要带 Bearer Token,应使用 fetch 获取 Blob,直接使用 a 标签或 window.open 无法附加该请求头。失败时按 JSON 错误响应处理。
|
||||
|
||||
### 社区目录和文件
|
||||
|
||||
- `GET /api/community/projects/{projectCode}/tree`:path 用法与工作区一致,data 为 Tree。
|
||||
- `GET /api/community/projects/{projectCode}/files`:支持 path、download,返回与工作区相同的文件数据或二进制。
|
||||
|
||||
均可匿名访问,固定读取当前 publishedCommitSha。**不要传 commitSha 参数,即使传空字符串也会返回 400。** 社区页面只读,需要编辑时先 Fork 到自己的工作区。撤回、删除或未发布项目返回 404。
|
||||
|
||||
### 路径限制
|
||||
|
||||
文件和非根目录路径必须为相对路径,最长 1024 字符。支持中文、空格和多级目录,例如 `models/轮式机器人/底盘.stl`;不加开头或结尾斜杠。根目录在目录接口和上传 directory 中用空字符串。
|
||||
|
||||
禁止绝对路径、反斜杠、空路径段、`.`、`..`、`.git` 路径段、冒号及控制字符。读取普通文件接口不支持符号链接或 Git 子模块。使用 URLSearchParams 处理查询编码,不自行拼接未编码的 path。
|
||||
|
||||
## 文件编辑与上传提交
|
||||
|
||||
### 多文件提交
|
||||
|
||||
`POST /api/workspace/projects/{projectCode}/commits`,需要登录。
|
||||
|
||||
| 请求字段 | 必填 | 约束 |
|
||||
| --- | --- | --- |
|
||||
| expectedCommitSha | 是 | 当前编辑所基于的完整工作区 SHA |
|
||||
| message | 是 | 非空,最多 1000 字符 |
|
||||
| changes | 是 | 1~500 个文件变更 |
|
||||
|
||||
每个 changes 元素使用以下字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| action | CREATE_FILE、UPDATE_FILE、DELETE_FILE、CREATE_DIRECTORY |
|
||||
| path | 文件或新目录的相对路径 |
|
||||
| content | CREATE_FILE、UPDATE_FILE 必填,UTF-8 文本;可为 `""` 创建或替换为空文件 |
|
||||
|
||||
请求示例中的路径必须符合仓库实际情况:创建路径应尚不存在,修改或删除目标必须存在。
|
||||
|
||||
```json
|
||||
{
|
||||
"expectedCommitSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"message": "更新说明并添加文件",
|
||||
"changes": [
|
||||
{ "action": "UPDATE_FILE", "path": "README.md", "content": "新的说明" },
|
||||
{ "action": "CREATE_FILE", "path": "src/main.txt", "content": "hello" },
|
||||
{ "action": "CREATE_DIRECTORY", "path": "models" },
|
||||
{ "action": "DELETE_FILE", "path": "old.txt" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
成功 data 为 Commit:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
"message": "更新说明并添加文件"
|
||||
}
|
||||
```
|
||||
|
||||
一次请求生成一个 Commit。保存成功后,更新编辑器基准 SHA 并重新加载目录和受影响的文件。编辑器输入只存在于当前前端状态中,后端没有自动保存或草稿接口。
|
||||
|
||||
新建空目录实际创建 `{path}/.gitkeep`,目录和文件会在提交时进入仓库。一批不能重复操作同一路径,包含新目录转换成 .gitkeep 后的实际路径。DELETE_FILE、CREATE_DIRECTORY 不需要 content。没有单独的删除目录或重命名接口;删除目录需提交其所有文件的删除操作,包括 .gitkeep,并遵守每批 500 个变更限制。
|
||||
|
||||
如果 expectedCommitSha 已不是最新 main,返回 409 CONFLICT。前端保留当前未提交输入,重新读取工作区版本,让用户处理差异后再提交;不要只替换 SHA 后自动覆盖内容。浏览历史版本时应使用只读模式,回到最新版本后再编辑。
|
||||
|
||||
### 上传并提交
|
||||
|
||||
`POST /api/workspace/projects/{projectCode}/uploads/commit`,需要登录,使用 FormData。
|
||||
|
||||
| multipart 字段 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| expectedCommitSha | 是 | 基于的当前工作区版本 |
|
||||
| message | 是 | 非空,最多 1000 字符 |
|
||||
| directory | 否 | 目标目录,省略或空字符串表示根目录 |
|
||||
| files | 是 | 重复使用同名 files 字段,1~500 个文件 |
|
||||
| paths | 否 | 重复使用同名 paths 字段,与 files 顺序和数量一一对应 |
|
||||
|
||||
不传 paths 时使用各文件的原始文件名;传入时每个值是相对于 directory 的路径。例:directory=`models`、paths=`robot/body.stl`,最终路径为 `models/robot/body.stl`,不要重复添加 directory 前缀。
|
||||
|
||||
同名文件会替换,界面应说明覆盖行为。所有文件生成一个 Commit,成功 data 与文本提交相同。上传用于二进制文件和较大文本文件的新增或替换。
|
||||
|
||||
### 默认大小限制
|
||||
|
||||
| 限制 | 数值 |
|
||||
| --- | --- |
|
||||
| 在线创建或编辑的单个文本内容 | 1 MiB,1048576 字节 |
|
||||
| 上传或读取的单文件 | 10 MiB,10485760 字节 |
|
||||
| 本次上传文件或提交内容总量 | 50 MiB,52428800 字节 |
|
||||
| multipart 整个请求 | 52 MiB,包含传输开销 |
|
||||
| 单批变更或上传文件数量 | 500 |
|
||||
|
||||
大小按字节计算,文本使用 UTF-8 编码长度,不使用 JavaScript 字符串 length 计算文件体积。以上是当前默认配置,超限返回 413。后端调整业务上传大小时还需同步调整 multipart 配置。
|
||||
|
||||
### 提交历史
|
||||
|
||||
`GET /api/workspace/projects/{projectCode}/commits?page=1&size=20`,需要登录。
|
||||
|
||||
data 为 PageResult<HistoryEntry>,只读取 main 的历史,不提供分支切换。历史条目示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
"message": "更新说明并添加文件",
|
||||
"authorName": "用户_11111111",
|
||||
"authorDate": "2026-10-13T08:40:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
点击历史条目,把 commitSha 传给工作区 tree、files 接口。历史 total 依赖仓库服务的统计响应头,未提供时退化为本页条数;前端也可结合本页 items 数量提供下一页操作。
|
||||
|
||||
## 社区发布和撤回
|
||||
|
||||
### 首次发布和更新社区版本
|
||||
|
||||
`PUT /api/workspace/projects/{projectCode}/publication`,需要登录。
|
||||
|
||||
请求:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
}
|
||||
```
|
||||
|
||||
commitSha 必须为当前 main 的完整 SHA,不能发布历史提交。成功 data 为 Project,publishStatus=PUBLISHED,publishedCommitSha 为提交的版本,publishedAt 更新为本次发布时间。
|
||||
|
||||
同一路径用于首次发布和以后手动更新社区版本。发布后继续提交、上传或创建目录,都不会自动更新社区代码。需要更新时,取得最新工作区 SHA,再调用此接口。项目名称、描述和类型的修改直接更新展示。
|
||||
|
||||
例:发布版本 A 后,在工作区提交得到 B,工作区展示 B,社区仍展示 A;再次用 B 调用 publication 后,社区才展示 B。前端可比较工作区 tree.commitSha 与项目 publishedCommitSha,显示“有未发布的更新”。
|
||||
|
||||
工作区 SHA 已变化时返回 409 CONFLICT,刷新版本后由用户重新确认发布。成功后刷新工作区详情和社区列表或详情。
|
||||
|
||||
### 撤回社区
|
||||
|
||||
`DELETE /api/workspace/projects/{projectCode}/publication`,需要登录,无请求体,成功 data 为 null。
|
||||
|
||||
撤回后项目留在工作区,社区列表、详情、目录、文件、评论列表及新增互动不可访问。原有评论、点赞和发布记录保留,再次发布继续使用;已有独立 Fork 不受影响。
|
||||
|
||||
## 社区详情和 Fork
|
||||
|
||||
### 项目详情
|
||||
|
||||
`GET /api/community/projects/{projectCode}`,可选登录,data 为 Project。
|
||||
|
||||
列表项点击后用 projectCode 进入前端详情路由,再请求本接口。可并行请求根目录和评论列表。需要当前用户的点赞状态时携带有效 Token。前端页面 URL 由前端定义,后端不返回可直接跳转的页面地址。
|
||||
|
||||
### Fork 到我的工作区
|
||||
|
||||
`POST /api/community/projects/{projectCode}/forks`,需要登录。
|
||||
|
||||
| 请求字段 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| name | 是 | 新项目名称,非空,最多 100 字符 |
|
||||
| publishedCommitSha | 是 | 当前社区详情返回的完整发布版本 |
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "我的机器人副本",
|
||||
"publishedCommitSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
}
|
||||
```
|
||||
|
||||
成功 data 为当前用户的新 Project,状态 READY、UNPUBLISHED;使用返回的新 projectCode 跳转工作区。类型和描述继承源项目,sourceProjectCode、sourceCommitSha 记录来源。
|
||||
|
||||
Fork 复制发布版本的所有普通文件,不复制源仓库提交历史,不自动同步上游。允许同一用户多次 Fork。所有文件复制完成才返回 READY;不支持符号链接或子模块。
|
||||
|
||||
源项目发布版本已变化时返回 409 CONFLICT,刷新社区详情后由用户重新确认。Fork 是同步请求,可能耗时较长;提交期间显示加载状态并防止重复点击。超时、网络断开或失败后先查询工作区,不要自动重发。
|
||||
|
||||
## 评论和点赞
|
||||
|
||||
### 评论列表
|
||||
|
||||
`GET /api/community/projects/{projectCode}/comments?page=1&size=20`,可选登录。
|
||||
|
||||
data 为 PageResult<Comment>,按创建时间倒序,平铺展示,不提供回复层级。评论 data 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"commentCode": "33333333333333333333333333333333",
|
||||
"author": {
|
||||
"userCode": "11111111111111111111111111111111",
|
||||
"nickname": "用户_11111111"
|
||||
},
|
||||
"content": "这个项目的结构很清楚",
|
||||
"createdAt": "2026-10-13T08:45:00"
|
||||
}
|
||||
```
|
||||
|
||||
### 新增评论
|
||||
|
||||
`POST /api/community/projects/{projectCode}/comments`,需要登录。
|
||||
|
||||
```json
|
||||
{
|
||||
"content": "这个项目的结构很清楚"
|
||||
}
|
||||
```
|
||||
|
||||
content 非空,最多 2000 字符,保存时去掉首尾空格。成功 data 为新 Comment。只支持纯文本,没有富文本、评论编辑或回复接口;前端以文本渲染。提交成功后刷新评论列表和项目 commentCount,不要自动重试新增评论请求。
|
||||
|
||||
### 删除自己的评论
|
||||
|
||||
`DELETE /api/comments/{commentCode}`,需要登录,无请求体,成功 data 为 null。
|
||||
|
||||
比较 `comment.author.userCode === currentUser.userCode` 决定是否显示删除入口,后端仍会校验作者身份。删除他人的、已删除的或不存在的评论返回 404。删除成功后刷新评论列表和项目统计。
|
||||
|
||||
### 点赞和取消点赞
|
||||
|
||||
- `PUT /api/community/projects/{projectCode}/like`:需要登录,点赞。
|
||||
- `DELETE /api/community/projects/{projectCode}/like`:需要登录,取消点赞。
|
||||
|
||||
均无请求体,成功 data 为 null,两者幂等。点赞接口不返回最新计数,成功后重新请求社区详情获取 liked、likeCount;可以先做乐观更新,失败时恢复并刷新详情。
|
||||
|
||||
## 错误码与前端处理
|
||||
|
||||
### 错误响应示例
|
||||
|
||||
版本冲突通常不带 data:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "CONFLICT",
|
||||
"message": "工作区版本已变化,请刷新后重新提交",
|
||||
"data": null,
|
||||
"requestId": "44444444444444444444444444444444"
|
||||
}
|
||||
```
|
||||
|
||||
部分创建、Fork 或仓库调用错误携带关联项目:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "REMOTE_RESULT_UNKNOWN",
|
||||
"message": "仓库连接异常或超时,写入结果需核对",
|
||||
"data": {
|
||||
"projectCode": "22222222222222222222222222222222"
|
||||
},
|
||||
"requestId": "44444444444444444444444444444444"
|
||||
}
|
||||
```
|
||||
|
||||
### 错误处理对照
|
||||
|
||||
| HTTP | code | 前端处理 |
|
||||
| --- | --- | --- |
|
||||
| 400 | BAD_REQUEST | 参数、分页、类型、路径、SHA 或文件操作不合法,展示 message 并检查请求 |
|
||||
| 400 | CAPTCHA_INVALID | 验证码错误、已使用或过期,刷新验证码 |
|
||||
| 401 | UNAUTHORIZED | 清除登录状态,受保护页面进入登录流程;公开 GET 可移除失效 Token 后重新读取 |
|
||||
| 403 | ACCOUNT_DISABLED | 登录账号不可用,停止登录流程并展示提示 |
|
||||
| 403 | FORBIDDEN | 无权访问,展示权限提示 |
|
||||
| 404 | NOT_FOUND | 项目不可访问、目标文件或版本不存在;停止加载目标资源并展示不可用状态 |
|
||||
| 405 | METHOD_NOT_ALLOWED | 检查请求方法 |
|
||||
| 409 | CONFLICT | 工作区或发布版本变化,或仓库未就绪,按 message 刷新版本或核对状态 |
|
||||
| 409 | GITEA_CONFLICT | 仓库内容冲突,刷新目录和文件后由用户处理 |
|
||||
| 409 | REMOTE_RESULT_UNKNOWN | 上一次仓库写入结果待核对,暂不能继续该项目的仓库写入 |
|
||||
| 413 | FILE_TOO_LARGE | 文件读取、编辑或上传内容超限,提示大小限制 |
|
||||
| 413 | UPLOAD_TOO_LARGE | 整体 multipart 请求超限 |
|
||||
| 415 | UNSUPPORTED_MEDIA_TYPE | 检查 Content-Type,JSON 与 FormData 不要混用 |
|
||||
| 500 | CAPTCHA_ERROR | 验证码生成失败,可重新获取并记录 requestId |
|
||||
| 500 | PROJECT_INITIALIZATION_ERROR | 项目初始化或回写未完成,查看 data.projectCode 和工作区,请后端核对 |
|
||||
| 500 | INTERNAL_ERROR | 展示服务异常并保留 requestId |
|
||||
| 502 | GITEA_ERROR | 仓库服务异常;写请求先核对结果,避免自动重试 |
|
||||
| 502 | GITEA_INVALID_RESPONSE | 仓库响应无法确认;写请求先核对结果,避免自动重试 |
|
||||
| 503 | GITEA_NOT_CONFIGURED | 后端缺少仓库配置,请后端处理 |
|
||||
| 504 | REMOTE_RESULT_UNKNOWN | 仓库连接异常或超时;读请求可重新读取,写请求需先核对结果 |
|
||||
|
||||
通过 HTTP 状态和 code 判断行为,保留 requestId 供排查。通用请求封装不要自动重试创建项目、Fork、评论或文件写入。浏览器超时、取消请求、连接中断不保证后端没有执行成功。
|
||||
|
||||
写入结果待核对时,同一进程内会阻止该项目后续仓库写入或发布;仍可读取可用文件、修改项目信息、撤回和删除。CREATING 项目因仓库尚未 READY,不能读取文件。没有 repository_operation 查询接口、自动恢复接口或跨重启完整幂等保证。
|
||||
|
||||
## 页面调用顺序
|
||||
|
||||
| 页面或操作 | 调用顺序 |
|
||||
| --- | --- |
|
||||
| 社区首页 | project-types → community/projects;选类型和关键词时重置页码 |
|
||||
| 社区详情 | community 项目详情、根目录、评论列表;展开目录或点击文件再读取对应内容 |
|
||||
| 登录页 | captcha → login;失败后刷新验证码;成功后保存平台登录状态 |
|
||||
| 我的工作区 | users/me → workspace/projects,分别显示仓库状态和发布状态 |
|
||||
| 创建项目 | POST workspace/projects → 使用返回 projectCode 进入详情 → tree 获取当前版本 |
|
||||
| 文件编辑 | workspace 详情与 tree → files → 判断 editable → commits → 刷新版本、目录和文件 |
|
||||
| 上传文件 | tree 获取基准 SHA → uploads/commit → 刷新目录和当前版本 |
|
||||
| 发布或更新社区 | 获取最新工作区 SHA → publication → 刷新项目和社区页面 |
|
||||
| Fork | 获取社区详情中的发布 SHA → forks → 使用新 projectCode 进入工作区 |
|
||||
| 评论或点赞 | 完成写请求 → 刷新评论或项目详情中的统计字段 |
|
||||
|
||||
## 前端请求示例
|
||||
|
||||
以下示例使用浏览器 fetch 和 TypeScript,类型声明见前面的响应结构。API_BASE 使用 `/api`,配合同域反向代理或开发代理。
|
||||
|
||||
### JSON 与 FormData 请求封装
|
||||
|
||||
```typescript
|
||||
const API_BASE = '/api';
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly requestId: string | null,
|
||||
readonly data: unknown = null,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
options: {
|
||||
method?: string;
|
||||
token?: string;
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
} = {},
|
||||
): Promise<T> {
|
||||
const headers = new Headers({ Accept: 'application/json' });
|
||||
if (options.token) headers.set('Authorization', `Bearer ${options.token}`);
|
||||
|
||||
let body: BodyInit | undefined;
|
||||
if (options.body instanceof FormData) {
|
||||
body = options.body; // 浏览器自动设置 multipart boundary
|
||||
} else if (options.body !== undefined) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
body = JSON.stringify(options.body);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}${path}`, {
|
||||
method: options.method ?? 'GET',
|
||||
headers,
|
||||
body,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
let result: ApiResponse<T>;
|
||||
try {
|
||||
result = await response.json();
|
||||
} catch {
|
||||
throw new ApiError(
|
||||
response.status,
|
||||
'BAD_RESPONSE', // 前端封装错误码,不是后端业务错误码
|
||||
'接口未返回有效 JSON',
|
||||
response.headers.get('X-Request-Id'),
|
||||
);
|
||||
}
|
||||
if (!response.ok || result.code !== 'OK') {
|
||||
throw new ApiError(
|
||||
response.status, result.code, result.message,
|
||||
result.requestId ?? response.headers.get('X-Request-Id'), result.data,
|
||||
);
|
||||
}
|
||||
return result.data as T; // 返回 null 的接口使用 request<null>
|
||||
}
|
||||
```
|
||||
|
||||
调用处捕获 ApiError,按照错误码表处理。fetch 的网络错误和 AbortError 也需要处理;对于写请求,这些错误同样先核对结果。此封装不自动重试,也不用于下载二进制。
|
||||
|
||||
### 列表和文件读取
|
||||
|
||||
```typescript
|
||||
async function loadProjects(type: string | undefined, keyword: string) {
|
||||
const query = new URLSearchParams({ page: '1', size: '20' });
|
||||
if (type) query.set('type', type);
|
||||
if (keyword.trim()) query.set('keyword', keyword.trim());
|
||||
return request<PageResult<Project>>(`/community/projects?${query}`);
|
||||
}
|
||||
|
||||
async function readWorkspaceFile(projectCode: string, path: string, token: string) {
|
||||
const query = new URLSearchParams({ path });
|
||||
return request<ProjectFile>(
|
||||
`/workspace/projects/${encodeURIComponent(projectCode)}/files?${query}`,
|
||||
{ token },
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
需要 liked 状态时,列表请求也传入有效 token。
|
||||
|
||||
### 上传示例
|
||||
|
||||
```typescript
|
||||
async function uploadFiles(
|
||||
projectCode: string,
|
||||
expectedCommitSha: string,
|
||||
files: File[],
|
||||
token: string,
|
||||
) {
|
||||
const form = new FormData();
|
||||
form.append('expectedCommitSha', expectedCommitSha);
|
||||
form.append('message', '上传模型文件');
|
||||
form.append('directory', 'models');
|
||||
for (const file of files) {
|
||||
form.append('files', file, file.name);
|
||||
form.append('paths', file.name); // 也可改为相对于 models 的多级路径
|
||||
}
|
||||
return request<Commit>(
|
||||
`/workspace/projects/${encodeURIComponent(projectCode)}/uploads/commit`,
|
||||
{ method: 'POST', token, body: form },
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 工作区下载示例
|
||||
|
||||
```typescript
|
||||
async function downloadWorkspaceFile(projectCode: string, path: string, token: string) {
|
||||
const query = new URLSearchParams({ path, download: 'true' });
|
||||
const response = await fetch(
|
||||
`${API_BASE}/workspace/projects/${encodeURIComponent(projectCode)}/files?${query}`,
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
);
|
||||
if (!response.ok) {
|
||||
const result = await response.json();
|
||||
throw new ApiError(
|
||||
response.status, result.code, result.message,
|
||||
result.requestId ?? response.headers.get('X-Request-Id'), result.data,
|
||||
);
|
||||
}
|
||||
const objectUrl = URL.createObjectURL(await response.blob());
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = path.split('/').pop() || 'download';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
|
||||
}
|
||||
```
|
||||
|
||||
### UTC 时间解析
|
||||
|
||||
只对项目、评论中不带时区的 UTC 字段使用这个函数;历史 authorDate 已带时区时按其原值解析。
|
||||
|
||||
```typescript
|
||||
function parseUtcTime(value: UtcDateTime): Date {
|
||||
const hasTimezone = /(?:Z|[+-]\d{2}:\d{2})$/i.test(value);
|
||||
return new Date(hasTimezone ? value : `${value}Z`);
|
||||
}
|
||||
```
|
||||
|
||||
### 开发代理示例
|
||||
|
||||
使用 Vite 时可在现有配置中加入以下 server 配置,保留 `/api` 路径,不进行 rewrite:
|
||||
|
||||
```typescript
|
||||
export default {
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8993',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## 后端人工核对
|
||||
|
||||
本节供前端遇到写入结果不明时与后端协作使用。记录 projectCode、requestId、接口路径及操作时间,提供给后端;不要在日志或工单中记录 Token、验证码答案、邮箱或文件内容。
|
||||
|
||||
后端先按 projectCode 对应的固定仓库名核对仓库、文件与提交历史。初始化未完成的项目核对后修正 repo_status 和仓库映射;确认没有远端写入仍在执行后,再重启后端解除本机待核对标记。超时不能直接视为未提交后再次写入。数据库结构见 [四表数据库说明](database.md)。
|
||||
@@ -0,0 +1,80 @@
|
||||
# 数据库初始化
|
||||
|
||||
业务数据库名为 `community`,只包含以下四张表。由人工执行;应用不运行迁移或自动建表。以下 SQL 面向 MySQL 8。
|
||||
|
||||
```sql
|
||||
CREATE DATABASE IF NOT EXISTS community CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE community;
|
||||
|
||||
CREATE TABLE sys_user (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部用户主键',
|
||||
user_code CHAR(32) NOT NULL COMMENT '用户业务编码',
|
||||
email VARCHAR(254) NOT NULL COMMENT '规范化后的登录邮箱',
|
||||
nickname VARCHAR(100) NOT NULL COMMENT '用户昵称',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' COMMENT '账号状态',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间 UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间 UTC',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_user_code (user_code),
|
||||
UNIQUE KEY uk_user_email (email)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台用户';
|
||||
|
||||
CREATE TABLE project (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部项目主键',
|
||||
project_code CHAR(32) NOT NULL COMMENT '项目业务编码',
|
||||
owner_user_id BIGINT NOT NULL COMMENT '所属平台用户',
|
||||
name VARCHAR(100) NOT NULL COMMENT '项目名称',
|
||||
description TEXT NOT NULL COMMENT '项目描述',
|
||||
project_type VARCHAR(64) NOT NULL COMMENT '配置中的项目类型编码',
|
||||
gitea_repo_id BIGINT NULL COMMENT 'Gitea 仓库标识',
|
||||
gitea_owner VARCHAR(100) NOT NULL COMMENT 'Gitea 仓库所属组织',
|
||||
gitea_repo_name VARCHAR(100) NOT NULL COMMENT 'Gitea 仓库名称',
|
||||
repo_status VARCHAR(16) NOT NULL DEFAULT 'CREATING' COMMENT '仓库状态 CREATING READY FAILED',
|
||||
publish_status VARCHAR(16) NOT NULL DEFAULT 'UNPUBLISHED' COMMENT '社区状态 UNPUBLISHED PUBLISHED',
|
||||
published_commit_sha VARCHAR(64) NULL COMMENT '社区已发布 Commit SHA',
|
||||
published_at DATETIME(3) NULL COMMENT '最近发布时间 UTC',
|
||||
source_project_id BIGINT NULL COMMENT 'Fork 来源项目',
|
||||
source_commit_sha VARCHAR(64) NULL COMMENT 'Fork 来源已发布 Commit SHA',
|
||||
deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除标识',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间 UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间 UTC',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_project_code (project_code),
|
||||
UNIQUE KEY uk_project_repo (gitea_owner, gitea_repo_name),
|
||||
UNIQUE KEY uk_project_repo_id (gitea_repo_id),
|
||||
KEY idx_project_owner (owner_user_id, deleted, created_at),
|
||||
KEY idx_project_community (publish_status, deleted, published_at),
|
||||
KEY idx_project_type (publish_status, deleted, project_type, published_at),
|
||||
CONSTRAINT fk_project_owner FOREIGN KEY (owner_user_id) REFERENCES sys_user(id),
|
||||
CONSTRAINT fk_project_source FOREIGN KEY (source_project_id) REFERENCES project(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户项目与社区发布';
|
||||
|
||||
CREATE TABLE project_comment (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部评论主键',
|
||||
comment_code CHAR(32) NOT NULL COMMENT '评论业务编码',
|
||||
project_id BIGINT NOT NULL COMMENT '所属项目',
|
||||
user_id BIGINT NOT NULL COMMENT '评论用户',
|
||||
content TEXT NOT NULL COMMENT '纯文本评论内容',
|
||||
deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除标识',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间 UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间 UTC',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_comment_code (comment_code),
|
||||
KEY idx_comment_project (project_id, deleted, created_at),
|
||||
CONSTRAINT fk_comment_project FOREIGN KEY (project_id) REFERENCES project(id),
|
||||
CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES sys_user(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目评论';
|
||||
|
||||
CREATE TABLE project_like (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部点赞主键',
|
||||
project_id BIGINT NOT NULL COMMENT '所属项目',
|
||||
user_id BIGINT NOT NULL COMMENT '点赞用户',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '点赞时间 UTC',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_like_project_user (project_id, user_id),
|
||||
CONSTRAINT fk_like_project FOREIGN KEY (project_id) REFERENCES project(id),
|
||||
CONSTRAINT fk_like_user FOREIGN KEY (user_id) REFERENCES sys_user(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目点赞';
|
||||
```
|
||||
|
||||
内部 ID 仅用于数据库关联,对外使用业务编码。时间均由后端写入 UTC。`CREATING` 项目表示仓库初始化未完成,不代表编辑草稿。Gitea 数据库与业务库分离,不修改 Gitea 内部表。
|
||||
@@ -0,0 +1,58 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.5.7</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<groupId>com.linkerbot</groupId>
|
||||
<artifactId>community</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>community-common</module>
|
||||
<module>community-bean</module>
|
||||
<module>community-service</module>
|
||||
<module>community-security</module>
|
||||
<module>community-api</module>
|
||||
</modules>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<mybatis-plus.version>3.5.11</mybatis-plus.version>
|
||||
<springdoc.version>2.8.14</springdoc.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-jsqlparser</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
COMMUNITY_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
if [[ -f "$COMMUNITY_ROOT/.env" ]]; then
|
||||
set -a
|
||||
source "$COMMUNITY_ROOT/.env"
|
||||
set +a
|
||||
fi
|
||||
export SPRING_PROFILES_ACTIVE="${SPRING_PROFILES_ACTIVE:-test}"
|
||||
cd "$COMMUNITY_ROOT"
|
||||
mvn -q -DskipTests package
|
||||
exec java -Djava.awt.headless=true -jar community-api/target/community-api-0.0.1-SNAPSHOT.jar "$@"
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""在临时 H2 数据库运行真实 Gitea 测试,清理本次创建的临时仓库。"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
environment = os.environ.copy()
|
||||
config = root / ".env"
|
||||
if config.exists():
|
||||
for line in config.read_text().splitlines():
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
parsed = shlex.split(value)
|
||||
if parsed:
|
||||
environment[key] = parsed[0]
|
||||
if not environment.get("GITEA_TOKEN"):
|
||||
raise SystemExit("请先配置 GITEA_TOKEN 和 GITEA_ORGANIZATION")
|
||||
environment["COMMUNITY_LIVE_GITEA"] = "true"
|
||||
raise SystemExit(subprocess.call([
|
||||
"mvn", "-q", "-Dtest=GiteaLiveTest", "-Dsurefire.failIfNoSpecifiedTests=false", "test"
|
||||
], cwd=root, env=environment))
|
||||
Reference in New Issue
Block a user