社区初始化
This commit is contained in:
@@ -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> {}
|
||||
Reference in New Issue
Block a user