包结构修改
This commit is contained in:
@@ -6,6 +6,18 @@ Spring Boot 社区后端,工程分层参考 cadworld。使用 Java 21、Spring
|
||||
|
||||
内置项目类型为 GENERAL(通用)、HUMANOID(人形)、QUADRUPED(四足)、WHEELED(轮式)。前端通过 `/api/project-types` 获取类型列表,用于项目创建、修改和列表筛选。
|
||||
|
||||
## 工程结构
|
||||
|
||||
| 模块 | 职责与主要包 |
|
||||
| --- | --- |
|
||||
| community-api | 应用入口、HTTP 接口和接口配置;使用 api.controller、api.config |
|
||||
| community-bean | 数据库实体在 bean.entity,请求与响应 record 集中在 bean.Contracts |
|
||||
| community-service | 业务 Service 接口在 service 根包,实现类在 service.impl;包含 mapper、config、gitea、support |
|
||||
| community-security | 平台登录会话、验证码、身份上下文、认证过滤器和安全配置 |
|
||||
| community-common | 通用响应、分页、异常处理、requestId 和基础工具 |
|
||||
|
||||
UserService、ProjectService、FileService、InteractionService 采用接口加实现类,Controller、安全模块和服务之间通过接口注入。GiteaClient 与 RestGiteaClient 定义仓库调用边界;项目锁、UTC 时间和分页检查归入 support。安全模块内的 TokenService、CaptchaService 保留具体类,首期沿用本机缓存。
|
||||
|
||||
## 功能与边界
|
||||
|
||||
支持邮箱加图片验证码登录、我的项目列表、在线文本编辑、新建文件和目录、上传及多文件提交、手动发布和撤回、已发布版本浏览、快照 Fork、平铺评论和点赞。工作区是用户项目列表,没有 workspace 表。没有 repository_operation 表、草稿保存、AI、类型表、标签、收藏、成员协作或管理后台。
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.linkerbot.community.api;
|
||||
package com.linkerbot.community.api.config;
|
||||
|
||||
import io.swagger.v3.oas.models.*;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.linkerbot.community.api;
|
||||
package com.linkerbot.community.api.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.linkerbot.community.api;
|
||||
package com.linkerbot.community.api.controller;
|
||||
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.linkerbot.community.api;
|
||||
package com.linkerbot.community.api.controller;
|
||||
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.linkerbot.community.api;
|
||||
package com.linkerbot.community.api.controller;
|
||||
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.common.*;
|
||||
@@ -1,264 +1,41 @@
|
||||
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 com.linkerbot.community.bean.Contracts.CommitInput;
|
||||
import com.linkerbot.community.bean.Contracts.CommitView;
|
||||
import com.linkerbot.community.bean.Contracts.FileView;
|
||||
import com.linkerbot.community.bean.Contracts.HistoryEntry;
|
||||
import com.linkerbot.community.bean.Contracts.TreeView;
|
||||
import com.linkerbot.community.common.PageResponse;
|
||||
import com.linkerbot.community.service.gitea.GiteaClient;
|
||||
|
||||
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.*;
|
||||
import java.util.List;
|
||||
|
||||
@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 interface FileService {
|
||||
TreeView ownerTree(long userId, String code, String path, String commitSha);
|
||||
|
||||
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);
|
||||
}
|
||||
TreeView communityTree(String code, String path);
|
||||
|
||||
public TreeView communityTree(String code, String path) {
|
||||
Project project = projects.published(code);
|
||||
return tree(project, project.getPublishedCommitSha(), path);
|
||||
}
|
||||
GiteaClient.StoredFile ownerFile(long userId, String code, String path, String commitSha);
|
||||
|
||||
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));
|
||||
}
|
||||
FileView ownerFileView(long userId, String code, String path, String commitSha);
|
||||
|
||||
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));
|
||||
}
|
||||
GiteaClient.StoredFile communityFile(String code, String 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)));
|
||||
}
|
||||
FileView communityFileView(String code, String 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));
|
||||
}
|
||||
CommitView commit(long userId, String code, CommitInput input);
|
||||
|
||||
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(
|
||||
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;
|
||||
});
|
||||
}
|
||||
List<String> paths);
|
||||
|
||||
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);
|
||||
}
|
||||
PageResponse<HistoryEntry> history(long userId, String code, long page, long size);
|
||||
}
|
||||
|
||||
+10
-98
@@ -1,106 +1,18 @@
|
||||
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 com.linkerbot.community.bean.Contracts.CommentInput;
|
||||
import com.linkerbot.community.bean.Contracts.CommentView;
|
||||
import com.linkerbot.community.common.PageResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
/** 社区评论和幂等点赞操作。 */
|
||||
public interface InteractionService {
|
||||
PageResponse<CommentView> list(String code, long page, long size);
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
CommentView comment(long userId, String code, CommentInput input);
|
||||
|
||||
@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;
|
||||
void deleteComment(long userId, String code);
|
||||
|
||||
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());
|
||||
}
|
||||
void like(long userId, String code);
|
||||
|
||||
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);
|
||||
}
|
||||
void unlike(long userId, String code);
|
||||
}
|
||||
|
||||
+26
-369
@@ -1,389 +1,46 @@
|
||||
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 com.linkerbot.community.bean.Contracts.ForkInput;
|
||||
import com.linkerbot.community.bean.Contracts.ProjectInput;
|
||||
import com.linkerbot.community.bean.Contracts.ProjectView;
|
||||
import com.linkerbot.community.bean.Contracts.TypeView;
|
||||
import com.linkerbot.community.bean.entity.Project;
|
||||
import com.linkerbot.community.common.PageResponse;
|
||||
import com.linkerbot.community.service.gitea.GiteaClient;
|
||||
|
||||
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.List;
|
||||
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 interface ProjectService {
|
||||
List<TypeView> types();
|
||||
|
||||
public static LocalDateTime now() {
|
||||
return LocalDateTime.now(Clock.systemUTC());
|
||||
}
|
||||
ProjectView view(Project project, Long currentUser);
|
||||
|
||||
public static void pageCheck(long page, long size) {
|
||||
if (page < 1 || page > 100000 || size < 1 || size > 100)
|
||||
throw BusinessException.badRequest("分页参数不合法");
|
||||
}
|
||||
PageResponse<ProjectView> list(
|
||||
Long ownerId, String type, String keyword, long page, long size, Long currentUser);
|
||||
|
||||
public List<TypeView> types() {
|
||||
return config.getTypes().entrySet().stream()
|
||||
.map(e -> new TypeView(e.getKey(), e.getValue()))
|
||||
.toList();
|
||||
}
|
||||
ProjectView create(long userId, ProjectInput input);
|
||||
|
||||
private void validateInput(ProjectInput input) {
|
||||
if (!config.getTypes().containsKey(input.projectType()))
|
||||
throw BusinessException.badRequest("项目类型不在可选列表中");
|
||||
}
|
||||
ProjectView fork(long userId, String sourceCode, ForkInput input);
|
||||
|
||||
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;
|
||||
}
|
||||
ProjectView update(long userId, String code, ProjectInput input);
|
||||
|
||||
public Project readyOwner(long userId, String code) {
|
||||
Project project = owner(userId, code);
|
||||
ready(project);
|
||||
return project;
|
||||
}
|
||||
void delete(long userId, String code);
|
||||
|
||||
public void ready(Project project) {
|
||||
if (!"READY".equals(project.getRepoStatus()))
|
||||
throw BusinessException.conflict("仓库尚未就绪,请核对项目创建状态");
|
||||
}
|
||||
ProjectView publish(long userId, String code, String expectedSha);
|
||||
|
||||
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;
|
||||
}
|
||||
void withdraw(long userId, String code);
|
||||
|
||||
public GiteaClient.Repository repository(Project project) {
|
||||
return new GiteaClient.Repository(
|
||||
project.getGiteaRepoId(), project.getGiteaOwner(), project.getGiteaRepoName());
|
||||
}
|
||||
Project owner(long userId, String code);
|
||||
|
||||
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());
|
||||
}
|
||||
Project readyOwner(long userId, String code);
|
||||
|
||||
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());
|
||||
}
|
||||
void ready(Project project);
|
||||
|
||||
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;
|
||||
}
|
||||
Project published(String code);
|
||||
|
||||
public ProjectView create(long userId, ProjectInput input) {
|
||||
users.require(userId);
|
||||
Project project = initialize(userId, input, null);
|
||||
return locks.write(project.getProjectCode(), () -> createRemote(project, null));
|
||||
}
|
||||
GiteaClient.Repository repository(Project project);
|
||||
|
||||
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)));
|
||||
}
|
||||
<T> T write(long userId, String code, Function<Project, T> action);
|
||||
}
|
||||
|
||||
@@ -1,70 +1,16 @@
|
||||
package com.linkerbot.community.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.linkerbot.community.bean.Contracts.*;
|
||||
import com.linkerbot.community.bean.Contracts.PublicUser;
|
||||
import com.linkerbot.community.bean.Contracts.UserView;
|
||||
import com.linkerbot.community.bean.entity.User;
|
||||
import com.linkerbot.community.common.*;
|
||||
import com.linkerbot.community.service.mapper.UserMapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
/** 平台用户查询、登录和公开信息转换。 */
|
||||
public interface UserService {
|
||||
User login(String email);
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
User require(long id);
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Locale;
|
||||
UserView view(User user);
|
||||
|
||||
@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());
|
||||
}
|
||||
PublicUser publicView(long id);
|
||||
}
|
||||
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
package com.linkerbot.community.service.impl;
|
||||
|
||||
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.FileService;
|
||||
import com.linkerbot.community.service.ProjectService;
|
||||
import com.linkerbot.community.service.UserService;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
import com.linkerbot.community.service.gitea.*;
|
||||
import com.linkerbot.community.service.support.ProjectSupport;
|
||||
|
||||
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 FileServiceImpl implements FileService {
|
||||
private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);
|
||||
private final ProjectService projects;
|
||||
private final UserService users;
|
||||
private final GiteaClient gitea;
|
||||
private final CommunityProperties config;
|
||||
|
||||
@Override
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
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));
|
||||
}
|
||||
|
||||
@Override
|
||||
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));
|
||||
}
|
||||
|
||||
@Override
|
||||
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)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public GiteaClient.StoredFile communityFile(String code, String path) {
|
||||
Project project = projects.published(code);
|
||||
return gitea.file(
|
||||
projects.repository(project),
|
||||
project.getPublishedCommitSha(),
|
||||
FilePaths.file(path));
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResponse<HistoryEntry> history(long userId, String code, long page, long size) {
|
||||
ProjectSupport.pageCheck(page, size);
|
||||
return gitea.history(projects.repository(projects.readyOwner(userId, code)), page, size);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.linkerbot.community.service.impl;
|
||||
|
||||
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.InteractionService;
|
||||
import com.linkerbot.community.service.ProjectService;
|
||||
import com.linkerbot.community.service.UserService;
|
||||
import com.linkerbot.community.service.mapper.*;
|
||||
import com.linkerbot.community.service.support.ProjectSupport;
|
||||
|
||||
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 InteractionServiceImpl implements InteractionService {
|
||||
private static final Logger log = LoggerFactory.getLogger(InteractionServiceImpl.class);
|
||||
private final ProjectService projects;
|
||||
private final UserService users;
|
||||
private final CommentMapper comments;
|
||||
private final LikeMapper likes;
|
||||
|
||||
@Override
|
||||
public PageResponse<CommentView> list(String code, long page, long size) {
|
||||
ProjectSupport.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());
|
||||
}
|
||||
|
||||
@Override
|
||||
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(ProjectSupport.now());
|
||||
comment.setUpdatedAt(comment.getCreatedAt());
|
||||
comments.insert(comment);
|
||||
log.info("新增评论 projectCode={} commentCode={}", code, comment.getCommentCode());
|
||||
return view(comment);
|
||||
}
|
||||
|
||||
@Override
|
||||
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, ProjectSupport.now()));
|
||||
if (count == 0) throw BusinessException.notFound();
|
||||
log.info("删除评论 commentCode={}", code);
|
||||
}
|
||||
|
||||
@Override
|
||||
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(ProjectSupport.now());
|
||||
try {
|
||||
likes.insert(like);
|
||||
} catch (DuplicateKeyException duplicate) {
|
||||
return;
|
||||
}
|
||||
log.info("点赞 projectCode={}", code);
|
||||
}
|
||||
|
||||
@Override
|
||||
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);
|
||||
}
|
||||
}
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
package com.linkerbot.community.service.impl;
|
||||
|
||||
import static com.linkerbot.community.service.support.ProjectSupport.now;
|
||||
import static com.linkerbot.community.service.support.ProjectSupport.pageCheck;
|
||||
|
||||
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.ProjectService;
|
||||
import com.linkerbot.community.service.UserService;
|
||||
import com.linkerbot.community.service.config.CommunityProperties;
|
||||
import com.linkerbot.community.service.gitea.*;
|
||||
import com.linkerbot.community.service.mapper.*;
|
||||
import com.linkerbot.community.service.support.ProjectLocks;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ProjectServiceImpl implements ProjectService {
|
||||
private static final Logger log = LoggerFactory.getLogger(ProjectServiceImpl.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;
|
||||
|
||||
@Override
|
||||
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("项目类型不在可选列表中");
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Project readyOwner(long userId, String code) {
|
||||
Project project = owner(userId, code);
|
||||
ready(project);
|
||||
return project;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ready(Project project) {
|
||||
if (!"READY".equals(project.getRepoStatus()))
|
||||
throw BusinessException.conflict("仓库尚未就绪,请核对项目创建状态");
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GiteaClient.Repository repository(Project project) {
|
||||
return new GiteaClient.Repository(
|
||||
project.getGiteaRepoId(), project.getGiteaOwner(), project.getGiteaRepoName());
|
||||
}
|
||||
|
||||
@Override
|
||||
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());
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProjectView create(long userId, ProjectInput input) {
|
||||
users.require(userId);
|
||||
Project project = initialize(userId, input, null);
|
||||
return locks.write(project.getProjectCode(), () -> createRemote(project, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
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 空仓库");
|
||||
}
|
||||
|
||||
@Override
|
||||
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));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
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)));
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.linkerbot.community.service.impl;
|
||||
|
||||
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.UserService;
|
||||
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 UserServiceImpl implements UserService {
|
||||
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
|
||||
private final UserMapper users;
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public User require(long id) {
|
||||
User user = users.selectById(id);
|
||||
if (user == null || !"ACTIVE".equals(user.getStatus()))
|
||||
throw new BusinessException(401, "UNAUTHORIZED", "请重新登录");
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserView view(User user) {
|
||||
return new UserView(user.getUserCode(), user.getNickname(), user.getEmail());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PublicUser publicView(long id) {
|
||||
User user = users.selectById(id);
|
||||
return user == null
|
||||
? new PublicUser(null, "已删除用户")
|
||||
: new PublicUser(user.getUserCode(), user.getNickname());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.linkerbot.community.service;
|
||||
package com.linkerbot.community.service.support;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.linkerbot.community.service.support;
|
||||
|
||||
import com.linkerbot.community.common.BusinessException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 项目、文件和互动服务共用的时间与分页约定。 */
|
||||
public final class ProjectSupport {
|
||||
private ProjectSupport() {}
|
||||
|
||||
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("分页参数不合法");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user