Initial project source
这个提交包含在:
+43
@@ -0,0 +1,43 @@
|
||||
package cn.aixunkeji.datagov.resource.privatefile;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.dev33.satoken.SaManager;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.time.Instant;
|
||||
|
||||
/** Fixed business routes. Shared same-token is a trust-domain boundary, not caller-service identity. */
|
||||
@Component
|
||||
public class PrivateBusinessFileAuthorizationGateway {
|
||||
@DubboReference(group = "aixun-datagov-private-file-dataproduct", version = "1.0.0", check = false, retries = 0)
|
||||
private AuthorizationOwner dataproduct;
|
||||
@DubboReference(group = "aixun-datagov-private-file-governance", version = "1.0.0", check = false, retries = 0)
|
||||
private AuthorizationOwner governance;
|
||||
@DubboReference(group = "aixun-datagov-private-file-dataops", version = "1.0.0", check = false, retries = 0)
|
||||
private AuthorizationOwner dataops;
|
||||
|
||||
AuthorizationDecision require(AuthorizationQuery query) {
|
||||
if (!Boolean.TRUE.equals(SaManager.getConfig().getCheckSameToken()))
|
||||
throw new IllegalStateException("PRIVATE_FILE_TRUST_DISABLED");
|
||||
// The business Owner resolves the persisted delegation, real current user/scope/permissions,
|
||||
// purpose/recipient/license/revocation. Merely matching supplied Context never grants access.
|
||||
AuthorizationOwner owner = switch (query.target().businessOwner()) {
|
||||
case "dataproduct" -> dataproduct;
|
||||
case "governance" -> governance;
|
||||
case "dataops" -> dataops;
|
||||
default -> throw new IllegalStateException("PRIVATE_FILE_OWNER_NOT_CONFIGURED");
|
||||
};
|
||||
AuthorizationDecision decision;
|
||||
try { decision = owner.authorize(query); }
|
||||
catch (RuntimeException failure) { throw new IllegalStateException("PRIVATE_FILE_OWNER_UNAVAILABLE"); }
|
||||
Instant now = Instant.now();
|
||||
if (decision == null || !query.equals(decision.query()) || decision.state() != State.AVAILABLE
|
||||
|| decision.observedAt().isAfter(now) || !decision.expiresAt().isAfter(now))
|
||||
throw new IllegalStateException("PRIVATE_FILE_DENIED");
|
||||
if ((query.action() == Action.COMPLETE || query.action() == Action.READ) && !decision.committedReference())
|
||||
throw new IllegalStateException("PRIVATE_FILE_REFERENCE_NOT_COMMITTED");
|
||||
if (query.action() == Action.CANCEL && decision.committedReference())
|
||||
throw new IllegalStateException("PRIVATE_FILE_ALREADY_REFERENCED");
|
||||
return decision;
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package cn.aixunkeji.datagov.resource.privatefile;
|
||||
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** The operation row commits independently of the consuming business transaction. */
|
||||
@Repository
|
||||
public class PrivateBusinessFileJdbcRepository {
|
||||
static final String PRIVATE_SERVICE = "datagov-local-pvt";
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate transactions;
|
||||
|
||||
public PrivateBusinessFileJdbcRepository(DataSource dataSource, PlatformTransactionManager manager) {
|
||||
jdbc = new JdbcTemplate(dataSource);
|
||||
transactions = new TransactionTemplate(manager);
|
||||
transactions.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
}
|
||||
|
||||
record Stored(long organization, long department, String operationKey, String descriptorSha,
|
||||
String payloadSha, String fileId, String storageKey, Target target,
|
||||
WriteState state, long offset, long producerActor) {
|
||||
Binding binding() {
|
||||
return new Binding(target.businessOwner(), target.objectType(), target.objectId(),
|
||||
target.artifactVersion(), fileId, "1", target.bytesSha256(), target.byteLength(),
|
||||
target.mime(), target.use(), target.derivedFromFileId(), target.derivationPolicyVersion());
|
||||
}
|
||||
WriteStatus view() { return new WriteStatus(operationKey, state, binding(), offset); }
|
||||
}
|
||||
|
||||
<T> T transaction(Supplier<T> work) {
|
||||
return Objects.requireNonNull(transactions.execute(status -> work.get()));
|
||||
}
|
||||
|
||||
Stored reserve(StageRequest request, String descriptorSha, String storageKey) {
|
||||
Context c = request.context();
|
||||
// The unique operation scope excludes Actor: a different currently authorized reviewer can recover.
|
||||
jdbc.update("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(sys_oss_business_binding) */ INTO sys_oss_business_binding
|
||||
(organization_id,department_id,operation_key,descriptor_sha256,payload_sha256,oss_id,
|
||||
storage_key,target_json,state,next_offset,producer_actor,created_at,updated_at,row_version)
|
||||
VALUES (?,?,?,?,?,?,?,?,'PREPARING',0,?,CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6),0)
|
||||
|
||||
""", c.organizationId(), c.departmentId(), request.operationKey(), descriptorSha,
|
||||
request.payloadSha256(), IdGeneratorUtil.nextLongId(), storageKey,
|
||||
JsonUtils.toJsonString(request.target()), c.actorId());
|
||||
Stored stored = find(new WriteQuery(c, request.operationKey()));
|
||||
if (!stored.descriptorSha().equals(descriptorSha) || !stored.payloadSha().equals(request.payloadSha256())
|
||||
|| !stored.target().equals(request.target())) throw new IllegalArgumentException("PRIVATE_FILE_CONFLICT");
|
||||
return stored;
|
||||
}
|
||||
|
||||
Stored find(WriteQuery query) {
|
||||
List<Stored> rows = jdbc.query("""
|
||||
SELECT * FROM sys_oss_business_binding
|
||||
WHERE organization_id=? AND department_id=? AND operation_key=? FOR UPDATE
|
||||
""", this::map, query.context().organizationId(), query.context().departmentId(), query.operationKey());
|
||||
if (rows.size() != 1) throw new IllegalArgumentException("PRIVATE_FILE_NOT_FOUND");
|
||||
return rows.getFirst();
|
||||
}
|
||||
|
||||
Stored findFile(FileQuery query) {
|
||||
List<Stored> rows = jdbc.query("""
|
||||
SELECT * FROM sys_oss_business_binding
|
||||
WHERE organization_id=? AND department_id=? AND oss_id=? FOR UPDATE
|
||||
""", this::map, query.context().organizationId(), query.context().departmentId(),
|
||||
Long.parseLong(query.binding().fileId()));
|
||||
if (rows.size() != 1) throw new IllegalArgumentException("PRIVATE_FILE_NOT_FOUND");
|
||||
Stored result = rows.getFirst();
|
||||
if (!result.binding().equals(query.binding()) || !result.target().purpose().equals(query.purpose())
|
||||
|| !result.target().recipientRef().equals(query.recipientRef()))
|
||||
throw new IllegalArgumentException("PRIVATE_FILE_BINDING");
|
||||
return result;
|
||||
}
|
||||
|
||||
void progress(Stored stored, long offset, WriteState state) {
|
||||
if (jdbc.update("""
|
||||
UPDATE sys_oss_business_binding SET next_offset=?,state=?,row_version=row_version+1,
|
||||
updated_at=CURRENT_TIMESTAMP(6) WHERE organization_id=? AND department_id=?
|
||||
AND operation_key=? AND state=? AND next_offset=?
|
||||
""", offset, state.name(), stored.organization(), stored.department(), stored.operationKey(),
|
||||
stored.state().name(), stored.offset()) != 1) throw new IllegalStateException("PRIVATE_FILE_CONFLICT");
|
||||
}
|
||||
|
||||
void bind(Stored stored, long actor) {
|
||||
// No publicly usable URL, and no general-purpose upload API can create this reserved service/key.
|
||||
jdbc.update("""
|
||||
INSERT INTO sys_oss
|
||||
(oss_id,file_name,original_name,file_suffix,url,ext1,service,create_dept,create_by,create_time,update_by,update_time)
|
||||
VALUES (?,?,?,?,? ,?, ?,?,?,CURRENT_TIMESTAMP(6),?,CURRENT_TIMESTAMP(6))
|
||||
""", Long.parseLong(stored.fileId()), stored.storageKey(), stored.target().originalName(),
|
||||
stored.storageKey().substring(stored.storageKey().lastIndexOf('.')), "", "{}",
|
||||
PRIVATE_SERVICE, stored.department(), actor, actor);
|
||||
progress(stored, stored.offset(), WriteState.BOUND);
|
||||
}
|
||||
void eraseKnowledge(Stored stored) {
|
||||
if(stored.state()!=WriteState.CANCELED) progress(stored,stored.offset(),WriteState.CANCELED);
|
||||
jdbc.update("DELETE FROM sys_oss WHERE oss_id=? AND service=? AND file_name=?",Long.parseLong(stored.fileId()),PRIVATE_SERVICE,stored.storageKey());
|
||||
}
|
||||
|
||||
private Stored map(ResultSet rs, int row) throws SQLException {
|
||||
return new Stored(rs.getLong("organization_id"), rs.getLong("department_id"),
|
||||
rs.getString("operation_key"), rs.getString("descriptor_sha256"), rs.getString("payload_sha256"),
|
||||
rs.getString("oss_id"), rs.getString("storage_key"),
|
||||
Objects.requireNonNull(JsonUtils.parseObject(rs.getString("target_json"), Target.class)),
|
||||
WriteState.valueOf(rs.getString("state")), rs.getLong("next_offset"), rs.getLong("producer_actor"));
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package cn.aixunkeji.datagov.resource.privatefile;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** One private-file provider. Business authorization callbacks must be real before use. */
|
||||
public class PrivateBusinessFileRpcService implements PrivateBusinessFileOwner {
|
||||
private final PrivateBusinessFileService service;
|
||||
public PrivateBusinessFileRpcService(PrivateBusinessFileService service) { this.service = service; }
|
||||
@Override public FileResolution resolveFile(FileQuery q) { return safe(() -> service.resolveFile(q)); }
|
||||
@Override public FileChunk readChunk(ChunkQuery q) { return safe(() -> service.readChunk(q)); }
|
||||
@Override public WriteStatus stage(StageRequest q) { return safe(() -> service.stage(q)); }
|
||||
@Override public WriteStatus append(AppendRequest q) { return safe(() -> service.append(q)); }
|
||||
@Override public WriteStatus finish(WriteQuery q) { return safe(() -> service.finish(q)); }
|
||||
@Override public WriteStatus status(WriteQuery q) { return safe(() -> service.status(q)); }
|
||||
@Override public WriteStatus complete(WriteQuery q) { return safe(() -> service.complete(q)); }
|
||||
@Override public WriteStatus cancel(WriteQuery q) { return safe(() -> service.cancel(q)); }
|
||||
@Override public FileChunk readStaged(StagedRead q) { return safe(() -> service.readStaged(q)); }
|
||||
@Override public WriteStatus eraseKnowledgeOriginal(WriteQuery q) { return safe(() -> service.eraseKnowledgeOriginal(q)); }
|
||||
private static <T> T safe(Supplier<T> call) {
|
||||
try { return call.get(); }
|
||||
catch (RuntimeException failure) {
|
||||
// SQL/transport/parser exceptions may contain data or paths: never propagate the cause.
|
||||
String code = failure.getMessage();
|
||||
if (code == null || !code.matches("PRIVATE_FILE_[A-Z_]{1,64}")) code = "PRIVATE_FILE_UNAVAILABLE";
|
||||
throw new IllegalStateException(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package cn.aixunkeji.datagov.resource.privatefile;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.aixunkeji.resource.storage.DataGovLocalFileStorage;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.function.Function;
|
||||
import static cn.aixunkeji.datagov.resource.privatefile.PrivateBusinessFileJdbcRepository.Stored;
|
||||
|
||||
@Service
|
||||
public class PrivateBusinessFileService {
|
||||
private final PrivateBusinessFileJdbcRepository repository;
|
||||
private final DataGovLocalFileStorage storage;
|
||||
private final PrivateBusinessFileAuthorizationGateway authorization;
|
||||
|
||||
public PrivateBusinessFileService(PrivateBusinessFileJdbcRepository repository, DataGovLocalFileStorage storage,
|
||||
PrivateBusinessFileAuthorizationGateway authorization) {
|
||||
this.repository = repository; this.storage = storage; this.authorization = authorization;
|
||||
}
|
||||
|
||||
public WriteStatus stage(StageRequest request) {
|
||||
String name=request.target().originalName().toLowerCase(java.util.Locale.ROOT);
|
||||
if(name.endsWith(".doc")&&!ingestionOriginal(request.target())) throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
if((name.endsWith(".md")||name.endsWith(".docx")||name.endsWith(".zip"))
|
||||
&&!knowledgeOriginal(request.target())&&!(ingestionOriginal(request.target())&&name.endsWith(".docx"))) throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
storage.validatePrivate(request.target().originalName(), request.target().byteLength());
|
||||
authorization.require(new AuthorizationQuery(request.context(), request.target(), Action.STAGE, null, request.operationKey()));
|
||||
return repository.transaction(() -> {
|
||||
Stored stored = repository.reserve(request, descriptor(request.target()),
|
||||
storage.newPrivateKey(request.target().originalName(), request.target().byteLength()));
|
||||
requireLive(stored);
|
||||
authorize(request.context(), stored, Action.STAGE);
|
||||
return stored.view();
|
||||
});
|
||||
}
|
||||
|
||||
public WriteStatus append(AppendRequest request) {
|
||||
return with(request.query(), Action.APPEND, stored -> {
|
||||
if (stored.state() != WriteState.PREPARING || request.offset() > stored.offset()
|
||||
|| request.offset() > stored.target().byteLength() - request.bytes().length)
|
||||
throw new IllegalStateException("PRIVATE_FILE_OFFSET");
|
||||
long end = request.offset() + request.bytes().length;
|
||||
if (request.offset() < stored.offset() && end > stored.offset())
|
||||
throw new IllegalStateException("PRIVATE_FILE_OFFSET");
|
||||
try {
|
||||
storage.appendPrivate(stored.storageKey(), request.offset(), request.bytes(), stored.target().byteLength());
|
||||
} catch (IOException failure) { throw new IllegalStateException("PRIVATE_FILE_WRITE_UNCONFIRMED"); }
|
||||
long next = Math.max(stored.offset(), end);
|
||||
authorize(request.query().context(), stored, Action.APPEND);
|
||||
repository.progress(stored, next, stored.state());
|
||||
return new WriteStatus(stored.operationKey(), stored.state(), stored.binding(), next);
|
||||
});
|
||||
}
|
||||
|
||||
public WriteStatus finish(WriteQuery query) {
|
||||
return with(query, Action.FINISH, stored -> {
|
||||
if (stored.state() == WriteState.BOUND || stored.state() == WriteState.STAGED) return stored.view();
|
||||
if (stored.offset() != stored.target().byteLength()) throw new IllegalStateException("PRIVATE_FILE_INCOMPLETE");
|
||||
byte[] bytes = read(stored);
|
||||
storage.validatePrivateContent(stored.target().originalName(), bytes, stored.target().mime());
|
||||
authorize(query.context(), stored, Action.FINISH);
|
||||
repository.progress(stored, stored.offset(), WriteState.STAGED);
|
||||
return new WriteStatus(stored.operationKey(), WriteState.STAGED, stored.binding(), stored.offset());
|
||||
});
|
||||
}
|
||||
|
||||
public WriteStatus status(WriteQuery query) {
|
||||
// Canceled status may be inspected only with current Owner authorization.
|
||||
return repository.transaction(() -> {
|
||||
Stored stored = repository.find(query); authorize(query.context(), stored, Action.STATUS); return stored.view();
|
||||
});
|
||||
}
|
||||
|
||||
public WriteStatus complete(WriteQuery query) {
|
||||
return with(query, Action.COMPLETE, stored -> {
|
||||
if (stored.state() == WriteState.BOUND) return stored.view();
|
||||
if (stored.state() != WriteState.STAGED) throw new IllegalStateException("PRIVATE_FILE_NOT_STAGED");
|
||||
read(stored);
|
||||
authorize(query.context(), stored, Action.COMPLETE);
|
||||
repository.bind(stored, query.context().actorId());
|
||||
return new WriteStatus(stored.operationKey(), WriteState.BOUND, stored.binding(), stored.offset());
|
||||
});
|
||||
}
|
||||
|
||||
public WriteStatus cancel(WriteQuery query) {
|
||||
return repository.transaction(() -> {
|
||||
Stored stored = repository.find(query);
|
||||
authorize(query.context(), stored, Action.CANCEL);
|
||||
if (stored.state() == WriteState.BOUND) throw new IllegalStateException("PRIVATE_FILE_ALREADY_BOUND");
|
||||
if (stored.state() != WriteState.CANCELED) repository.progress(stored, stored.offset(), WriteState.CANCELED);
|
||||
// Logical isolation only. Never delete bytes on timeout, age alone or an unknown business commit.
|
||||
return new WriteStatus(stored.operationKey(), WriteState.CANCELED, stored.binding(), stored.offset());
|
||||
});
|
||||
}
|
||||
public WriteStatus eraseKnowledgeOriginal(WriteQuery query) {
|
||||
return repository.transaction(()->{
|
||||
Stored stored=repository.find(query);
|
||||
if(!knowledgeOriginal(stored.target())) throw new IllegalStateException("PRIVATE_FILE_ERASE_DENIED");
|
||||
authorize(query.context(),stored,Action.ERASE_KNOWLEDGE);
|
||||
try { storage.erasePrivateKnowledge(stored.storageKey()); }
|
||||
catch(IOException e) { throw new IllegalStateException("PRIVATE_FILE_ERASE_UNKNOWN"); }
|
||||
repository.eraseKnowledge(stored);
|
||||
return new WriteStatus(stored.operationKey(),WriteState.CANCELED,stored.binding(),stored.offset());
|
||||
});
|
||||
}
|
||||
private static boolean knowledgeOriginal(Target t) { return "governance".equals(t.businessOwner())&&"WORKBENCH_KNOWLEDGE_ATTACHMENT".equals(t.objectType())&&"KNOWLEDGE_ORIGINAL".equals(t.purpose())&&t.use()==FileUse.EVIDENCE; }
|
||||
private static boolean ingestionOriginal(Target t) { return "dataops".equals(t.businessOwner())&&"INGESTION_ORIGINAL_FILE".equals(t.objectType())&&"INGESTION_ORIGINAL_FILE".equals(t.purpose())&&t.use()==FileUse.EVIDENCE; }
|
||||
|
||||
public FileResolution resolveFile(FileQuery query) {
|
||||
return repository.transaction(() -> {
|
||||
Stored stored = repository.findFile(query); requireBound(stored);
|
||||
return resolution(query, authorize(query.context(), stored, Action.READ));
|
||||
});
|
||||
}
|
||||
|
||||
public FileChunk readChunk(ChunkQuery query) {
|
||||
return repository.transaction(() -> {
|
||||
Stored stored = repository.findFile(query.file()); requireBound(stored);
|
||||
authorize(query.file().context(), stored, Action.READ);
|
||||
byte[] bytes = read(stored);
|
||||
AuthorizationDecision decision = authorize(query.file().context(), stored, Action.READ);
|
||||
return chunk(query, bytes, decision);
|
||||
});
|
||||
}
|
||||
|
||||
public FileChunk readStaged(StagedRead query) {
|
||||
return with(query.query(), Action.VERIFY, stored -> {
|
||||
if (stored.state() != WriteState.STAGED && stored.state() != WriteState.BOUND)
|
||||
throw new IllegalStateException("PRIVATE_FILE_NOT_STAGED");
|
||||
byte[] bytes = read(stored);
|
||||
AuthorizationDecision decision = authorize(query.query().context(), stored,
|
||||
stored.state() == WriteState.BOUND ? Action.READ : Action.VERIFY);
|
||||
FileQuery file = new FileQuery(query.query().context(), stored.binding(),
|
||||
stored.target().purpose(), stored.target().recipientRef());
|
||||
return chunk(new ChunkQuery(file, query.offset(), query.maximumBytes()), bytes, decision);
|
||||
});
|
||||
}
|
||||
|
||||
private <T> T with(WriteQuery query, Action action, Function<Stored,T> operation) {
|
||||
return repository.transaction(() -> {
|
||||
Stored stored = repository.find(query); requireLive(stored);
|
||||
authorize(query.context(), stored, action);
|
||||
return operation.apply(stored);
|
||||
});
|
||||
}
|
||||
|
||||
private AuthorizationDecision authorize(Context context, Stored stored, Action action) {
|
||||
return authorization.require(new AuthorizationQuery(context, stored.target(), action,
|
||||
stored.binding(), stored.operationKey()));
|
||||
}
|
||||
|
||||
private byte[] read(Stored stored) {
|
||||
try { return storage.readPrivate(stored.storageKey(), stored.target().byteLength(), stored.target().bytesSha256()); }
|
||||
catch (IOException failure) { throw new IllegalStateException("PRIVATE_FILE_INTEGRITY"); }
|
||||
}
|
||||
|
||||
private static void requireLive(Stored stored) {
|
||||
if (stored.state() == WriteState.CANCELED) throw new IllegalStateException("PRIVATE_FILE_CANCELED");
|
||||
}
|
||||
private static void requireBound(Stored stored) {
|
||||
if (stored.state() != WriteState.BOUND) throw new IllegalStateException("PRIVATE_FILE_NOT_BOUND");
|
||||
}
|
||||
private static FileResolution resolution(FileQuery query, AuthorizationDecision decision) {
|
||||
return new FileResolution(query, decision.state(), decision.decisionRef(), decision.authorizationVersion(),
|
||||
decision.revocationRef(), decision.observedAt(), decision.expiresAt(), null);
|
||||
}
|
||||
private static FileChunk chunk(ChunkQuery query, byte[] bytes, AuthorizationDecision decision) {
|
||||
int start = Math.toIntExact(query.offset());
|
||||
int end = (int) Math.min((long) start + query.maximumBytes(), bytes.length);
|
||||
byte[] slice = Arrays.copyOfRange(bytes, start, end);
|
||||
return new FileChunk(query, resolution(query.file(), decision), slice, hash(slice), end,
|
||||
end == bytes.length, "sha256:" + query.file().binding().bytesSha256());
|
||||
}
|
||||
private static String descriptor(Target target) {
|
||||
// Record serialization is not used for identity: length-prefixed exact fields, including nulls.
|
||||
String[] fields = {target.businessOwner(), target.objectType(), target.objectId(),
|
||||
Long.toString(target.artifactVersion()), target.use().name(), target.purpose(), target.recipientRef(),
|
||||
target.originalName(), target.bytesSha256(), Long.toString(target.byteLength()), target.mime(),
|
||||
target.derivedFromFileId(), target.derivationPolicyVersion()};
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
for (String field : fields) {
|
||||
byte[] bytes = field == null ? new byte[0] : field.getBytes(StandardCharsets.UTF_8);
|
||||
digest.update(java.nio.ByteBuffer.allocate(4).putInt(field == null ? -1 : bytes.length).array());
|
||||
digest.update(bytes);
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
} catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
private static String hash(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package cn.aixunkeji.resource;
|
||||
|
||||
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
|
||||
import cn.aixunkeji.datagov.resource.privatefile.PrivateBusinessFileService;
|
||||
import cn.aixunkeji.datagov.resource.privatefile.PrivateBusinessFileJdbcRepository;
|
||||
import cn.aixunkeji.datagov.resource.privatefile.PrivateBusinessFileRpcService;
|
||||
import cn.aixunkeji.datagov.resource.privatefile.PrivateBusinessFileAuthorizationGateway;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner;
|
||||
import org.apache.dubbo.config.spring.ServiceBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* 资源服务
|
||||
*
|
||||
*/
|
||||
@EnableDubbo
|
||||
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
|
||||
@Import({PrivateBusinessFileService.class, PrivateBusinessFileJdbcRepository.class,
|
||||
PrivateBusinessFileRpcService.class, PrivateBusinessFileAuthorizationGateway.class})
|
||||
public class AiXunResourceApplication {
|
||||
/** Exact explicit export; the private package is not broadly component/Dubbo scanned. */
|
||||
@Bean
|
||||
ServiceBean<PrivateBusinessFileOwner> privateBusinessFileExport(PrivateBusinessFileRpcService provider,
|
||||
org.springframework.context.ApplicationContext context) {
|
||||
ServiceBean<PrivateBusinessFileOwner> service = new ServiceBean<>(context);
|
||||
service.setInterface(PrivateBusinessFileOwner.class);
|
||||
service.setRef(provider);
|
||||
service.setGroup(PrivateBusinessFileOwner.GROUP);
|
||||
service.setVersion(PrivateBusinessFileOwner.VERSION);
|
||||
service.setRetries(0);
|
||||
return service;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(AiXunResourceApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 资源服务模块启动成功 ლ(´ڡ`ლ)゙ ");
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package cn.aixunkeji.resource.controller;
|
||||
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import cn.aixunkeji.common.core.constant.Constants;
|
||||
import cn.aixunkeji.common.core.constant.GlobalConstants;
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.core.utils.SpringUtils;
|
||||
import cn.aixunkeji.common.core.utils.regex.RegexValidator;
|
||||
import cn.aixunkeji.common.mail.config.properties.MailProperties;
|
||||
import cn.aixunkeji.common.mail.core.MailBuilder;
|
||||
import cn.aixunkeji.common.redis.annotation.RateLimiter;
|
||||
import cn.aixunkeji.common.redis.utils.RedisUtils;
|
||||
import cn.aixunkeji.common.web.core.BaseController;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* 邮件功能
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@ConditionalOnProperty(value = "mail.enabled", havingValue = "true")
|
||||
@RequestMapping("/email")
|
||||
public class SysEmailController extends BaseController {
|
||||
|
||||
private final MailProperties mailProperties;
|
||||
|
||||
/**
|
||||
* 发送邮箱验证码
|
||||
*
|
||||
* @param email 邮箱
|
||||
*/
|
||||
@GetMapping("/code")
|
||||
public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
|
||||
if (!mailProperties.getEnabled()) {
|
||||
return R.fail("当前系统没有开启邮箱功能!");
|
||||
}
|
||||
if (!RegexValidator.isEmail(email)) {
|
||||
return R.fail("请输入正确的邮箱地址!");
|
||||
}
|
||||
SpringUtils.getAopProxy(this).emailCodeImpl(email);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮箱验证码
|
||||
* 独立方法避免验证码关闭之后仍然走限流
|
||||
*/
|
||||
@RateLimiter(key = "#email", time = 60, count = 1)
|
||||
public void emailCodeImpl(String email) {
|
||||
String key = GlobalConstants.CAPTCHA_CODE_KEY + email;
|
||||
String code = RandomUtil.randomNumbers(4);
|
||||
try {
|
||||
MailBuilder.of()
|
||||
.to(email)
|
||||
.subject("登录验证码")
|
||||
.text("您本次验证码为:" + code + ",有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟,请尽快填写。")
|
||||
.send();
|
||||
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
|
||||
} catch (Exception e) {
|
||||
log.error("验证码短信发送异常 => {}", e.getMessage());
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package cn.aixunkeji.resource.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.common.web.core.BaseController;
|
||||
import cn.aixunkeji.resource.domain.vo.SysMessageBoxVo;
|
||||
import cn.aixunkeji.resource.service.ISysMessageService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 消息记录控制器
|
||||
*
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/message")
|
||||
public class SysMessageController extends BaseController {
|
||||
|
||||
private final ISysMessageService messageService;
|
||||
|
||||
@GetMapping("/box")
|
||||
public R<SysMessageBoxVo> getBox() {
|
||||
return R.ok(messageService.queryMessageBox(LoginHelper.getUserId()));
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package cn.aixunkeji.resource.controller;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import cn.aixunkeji.common.core.domain.PageResult;
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.core.validate.AddGroup;
|
||||
import cn.aixunkeji.common.core.validate.EditGroup;
|
||||
import cn.aixunkeji.common.core.validate.QueryGroup;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.aixunkeji.common.mybatis.core.page.PageQuery;
|
||||
import cn.aixunkeji.common.redis.annotation.RepeatSubmit;
|
||||
import cn.aixunkeji.common.web.core.BaseController;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssConfigBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssConfigVo;
|
||||
import cn.aixunkeji.resource.service.ISysOssConfigService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 对象存储配置Controller
|
||||
*
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/oss/config")
|
||||
public class SysOssConfigController extends BaseController {
|
||||
|
||||
private final ISysOssConfigService ossConfigService;
|
||||
|
||||
/**
|
||||
* 查询对象存储配置列表
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:list")
|
||||
@GetMapping("/list")
|
||||
public R<PageResult<SysOssConfigVo>> list(@Validated(QueryGroup.class) SysOssConfigBo bo, PageQuery pageQuery) {
|
||||
return R.ok(ossConfigService.queryPageList(bo, pageQuery));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取对象存储配置详细信息
|
||||
*
|
||||
* @param ossConfigId OSS配置ID
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:list")
|
||||
@GetMapping("/{ossConfigId}")
|
||||
public R<SysOssConfigVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("ossConfigId") Long ossConfigId) {
|
||||
return R.ok(ossConfigService.queryById(ossConfigId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增对象存储配置
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:add")
|
||||
@Log(title = "对象存储配置", businessType = BusinessType.INSERT)
|
||||
@PostMapping()
|
||||
public R<Void> add(@Validated(AddGroup.class) @RequestBody SysOssConfigBo bo) {
|
||||
return toAjax(ossConfigService.insertByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改对象存储配置
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:edit")
|
||||
@Log(title = "对象存储配置", businessType = BusinessType.UPDATE)
|
||||
@PutMapping()
|
||||
public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysOssConfigBo bo) {
|
||||
return toAjax(ossConfigService.updateByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除对象存储配置
|
||||
*
|
||||
* @param ossConfigIds OSS配置ID串
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:remove")
|
||||
@Log(title = "对象存储配置", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ossConfigIds}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossConfigIds) {
|
||||
return toAjax(ossConfigService.deleteWithValidByIds(Arrays.asList(ossConfigIds), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态修改
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:edit")
|
||||
@Log(title = "对象存储状态修改", businessType = BusinessType.UPDATE)
|
||||
@RepeatSubmit()
|
||||
@PutMapping("/changeStatus")
|
||||
public R<Void> changeStatus(@RequestBody SysOssConfigBo bo) {
|
||||
return toAjax(ossConfigService.updateOssConfigStatus(bo));
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package cn.aixunkeji.resource.controller;
|
||||
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import cn.aixunkeji.common.core.domain.PageResult;
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.core.validate.QueryGroup;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.aixunkeji.common.mybatis.core.page.PageQuery;
|
||||
import cn.aixunkeji.common.web.core.BaseController;
|
||||
import cn.aixunkeji.resource.domain.SysOssExt;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssUploadVo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssVo;
|
||||
import cn.aixunkeji.resource.service.ISysOssService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件上传 控制层
|
||||
*
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/oss")
|
||||
public class SysOssController extends BaseController {
|
||||
|
||||
private final ISysOssService ossService;
|
||||
|
||||
/**
|
||||
* 查询OSS对象存储列表
|
||||
*/
|
||||
@SaCheckPermission("system:oss:list")
|
||||
@GetMapping("/list")
|
||||
public R<PageResult<SysOssVo>> list(@Validated(QueryGroup.class) SysOssBo bo, PageQuery pageQuery) {
|
||||
return R.ok(ossService.queryPageList(bo, pageQuery));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询OSS对象基于id串
|
||||
*
|
||||
* @param ossIds OSS对象ID串
|
||||
*/
|
||||
@SaCheckPermission("system:oss:query")
|
||||
@GetMapping("/listByIds/{ossIds}")
|
||||
public R<List<SysOssVo>> listByIds(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossIds) {
|
||||
List<SysOssVo> list = ossService.listByIds(Arrays.asList(ossIds));
|
||||
return R.ok(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传OSS对象存储
|
||||
*
|
||||
* @param file 文件
|
||||
*/
|
||||
@SaCheckPermission("system:oss:upload")
|
||||
@Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
|
||||
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public R<SysOssUploadVo> upload(@RequestPart("file") MultipartFile file, @RequestParam(value = "ossExt", required = false) String ossExtJson) {
|
||||
SysOssVo oss = ossService.upload(file, JsonUtils.parseObject(ossExtJson, SysOssExt.class));
|
||||
SysOssUploadVo uploadVo = new SysOssUploadVo();
|
||||
uploadVo.setUrl(oss.getUrl());
|
||||
uploadVo.setFileName(oss.getOriginalName());
|
||||
uploadVo.setOssId(oss.getOssId().toString());
|
||||
return R.ok(uploadVo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载OSS对象
|
||||
*
|
||||
* @param ossId OSS对象ID
|
||||
* @throws IOException IO 异常
|
||||
*/
|
||||
@SaCheckPermission("system:oss:download")
|
||||
@GetMapping("/download/{ossId}")
|
||||
public ResponseEntity<byte[]> download(@PathVariable Long ossId) throws IOException {
|
||||
return ossService.download(ossId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除OSS对象存储
|
||||
*
|
||||
* @param ossIds OSS对象ID串
|
||||
*/
|
||||
@SaCheckPermission("system:oss:remove")
|
||||
@Log(title = "OSS对象存储", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ossIds}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossIds) {
|
||||
return toAjax(ossService.deleteWithValidByIds(Arrays.asList(ossIds), true));
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package cn.aixunkeji.resource.controller;
|
||||
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import cn.aixunkeji.common.core.constant.Constants;
|
||||
import cn.aixunkeji.common.core.constant.GlobalConstants;
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.core.utils.regex.RegexValidator;
|
||||
import cn.aixunkeji.common.redis.annotation.RateLimiter;
|
||||
import cn.aixunkeji.common.redis.utils.RedisUtils;
|
||||
import cn.aixunkeji.common.web.core.BaseController;
|
||||
import org.dromara.sms4j.api.SmsBlend;
|
||||
import org.dromara.sms4j.api.entity.SmsResponse;
|
||||
import org.dromara.sms4j.core.factory.SmsFactory;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
/**
|
||||
* 短信功能
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@ConditionalOnProperty(value = "sms.enabled", havingValue = "true")
|
||||
@RequestMapping("/sms")
|
||||
public class SysSmsController extends BaseController {
|
||||
|
||||
/**
|
||||
* 短信验证码
|
||||
*
|
||||
* @param phoneNumber 用户手机号
|
||||
*/
|
||||
@RateLimiter(key = "#phoneNumber", time = 60, count = 1)
|
||||
@GetMapping("/code")
|
||||
public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phoneNumber) {
|
||||
if (!RegexValidator.isMobile(phoneNumber)) {
|
||||
return R.fail("请输入正确的手机号!");
|
||||
}
|
||||
String key = GlobalConstants.CAPTCHA_CODE_KEY + phoneNumber;
|
||||
String code = RandomUtil.randomNumbers(4);
|
||||
// 验证码模板id 自行处理 (查数据库或写死均可)
|
||||
String templateId = "";
|
||||
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
|
||||
map.put("code", code);
|
||||
SmsBlend smsBlend = SmsFactory.getSmsBlend("tx1");
|
||||
SmsResponse smsResponse = smsBlend.sendMessage(phoneNumber, templateId, map);
|
||||
if (!smsResponse.isSuccess()) {
|
||||
log.error("验证码短信发送异常 => {}", smsResponse);
|
||||
Object data = smsResponse.getData();
|
||||
return R.fail(data == null ? "验证码短信发送失败" : data.toString());
|
||||
}
|
||||
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cn.aixunkeji.resource.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import cn.aixunkeji.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* 消息记录表 sys_message
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_message")
|
||||
public class SysMessage extends BaseEntity {
|
||||
|
||||
@TableId(value = "message_id")
|
||||
private Long messageId;
|
||||
|
||||
private String category;
|
||||
|
||||
private String type;
|
||||
|
||||
private String source;
|
||||
|
||||
private String title;
|
||||
|
||||
private String message;
|
||||
|
||||
private String content;
|
||||
|
||||
private String dataJson;
|
||||
|
||||
private String path;
|
||||
|
||||
private String sendUserIds;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cn.aixunkeji.resource.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import cn.aixunkeji.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* OSS对象存储对象
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_oss")
|
||||
public class SysOss extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
@TableId(value = "oss_id")
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package cn.aixunkeji.resource.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import cn.aixunkeji.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* 对象存储配置对象 sys_oss_config
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_oss_config")
|
||||
public class SysOssConfig extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@TableId(value = "oss_config_id")
|
||||
private Long ossConfigId;
|
||||
|
||||
/**
|
||||
* 配置key
|
||||
*/
|
||||
private String configKey;
|
||||
|
||||
/**
|
||||
* accessKey
|
||||
*/
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
private String prefix;
|
||||
|
||||
/**
|
||||
* 访问站点
|
||||
*/
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String domainUrl;
|
||||
|
||||
|
||||
/**
|
||||
* 是否https(0否 1是)
|
||||
*/
|
||||
private String isHttps;
|
||||
|
||||
/**
|
||||
* 域
|
||||
*/
|
||||
private String region;
|
||||
|
||||
/**
|
||||
* 是否默认(Y=是,N=否)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 桶权限类型(0private 1public 2custom)
|
||||
*/
|
||||
private String accessPolicy;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package cn.aixunkeji.resource.domain;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 附件扩展字段对象(存储在 SysOss.ext1 的 JSON 字符串中)
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
public class SysOssExt implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 所属业务类型(如 avatar、report、contract)
|
||||
*/
|
||||
private String bizType;
|
||||
|
||||
/**
|
||||
* 文件大小(单位:字节)
|
||||
*/
|
||||
private Long fileSize;
|
||||
|
||||
/**
|
||||
* 文件类型(MIME类型,如 image/png)
|
||||
*/
|
||||
private String contentType;
|
||||
|
||||
/**
|
||||
* 来源标识(如 userUpload、systemImport)
|
||||
*/
|
||||
private String source;
|
||||
|
||||
/**
|
||||
* 上传 IP 地址,便于审计和追踪
|
||||
*/
|
||||
private String uploadIp;
|
||||
|
||||
/**
|
||||
* 附件说明或备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 附件标签,如 ["图片", "证件"]
|
||||
*/
|
||||
private List<String> tags;
|
||||
|
||||
/**
|
||||
* 业务绑定ID(如某业务记录ID)
|
||||
*/
|
||||
private String refId;
|
||||
|
||||
/**
|
||||
* 绑定业务类型
|
||||
*/
|
||||
private String refType;
|
||||
|
||||
/**
|
||||
* 是否为临时文件,用于区分正式或待清理
|
||||
*/
|
||||
private Boolean isTemp;
|
||||
|
||||
/**
|
||||
* 文件MD5值(可用于去重或校验)
|
||||
*/
|
||||
private String md5;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package cn.aixunkeji.resource.domain.bo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import cn.aixunkeji.resource.domain.SysOss;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OSS对象存储分页查询对象 sys_oss
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
@AutoMapper(target = SysOss.class, reverseConvertGenerate = false)
|
||||
public class SysOssBo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* ossId
|
||||
*/
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
/**
|
||||
* 创建者
|
||||
*/
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
private Map<String, Object> params = new HashMap<>();
|
||||
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package cn.aixunkeji.resource.domain.bo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import cn.aixunkeji.common.core.validate.AddGroup;
|
||||
import cn.aixunkeji.common.core.validate.EditGroup;
|
||||
import cn.aixunkeji.resource.domain.SysOssConfig;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 对象存储配置业务对象 sys_oss_config
|
||||
*
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Data
|
||||
@AutoMapper(target = SysOssConfig.class, reverseConvertGenerate = false)
|
||||
public class SysOssConfigBo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
|
||||
private Long ossConfigId;
|
||||
|
||||
/**
|
||||
* 配置key
|
||||
*/
|
||||
@NotBlank(message = "配置key不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "configKey长度必须介于2和20 之间")
|
||||
private String configKey;
|
||||
|
||||
/**
|
||||
* accessKey
|
||||
*/
|
||||
@NotBlank(message = "accessKey不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "accessKey长度必须介于2和100 之间")
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
@NotBlank(message = "secretKey不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "secretKey长度必须介于2和100 之间")
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 桶名称
|
||||
*/
|
||||
@NotBlank(message = "桶名称不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "bucketName长度必须介于2和100之间")
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
private String prefix;
|
||||
|
||||
/**
|
||||
* 访问站点
|
||||
*/
|
||||
@NotBlank(message = "访问站点不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "endpoint长度必须介于2和100之间")
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String domainUrl;
|
||||
|
||||
/**
|
||||
* 是否https(Y=是,N=否)
|
||||
*/
|
||||
private String isHttps;
|
||||
|
||||
/**
|
||||
* 是否默认(Y=是,N=否)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 域
|
||||
*/
|
||||
private String region;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 桶权限类型(0private 1public 2custom)
|
||||
*/
|
||||
@NotBlank(message = "桶权限类型不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
private String accessPolicy;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
private Map<String, Object> params = new HashMap<>();
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package cn.aixunkeji.resource.domain.convert;
|
||||
|
||||
import io.github.linpeilie.BaseMapper;
|
||||
import cn.aixunkeji.resource.api.domain.RemoteFile;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssVo;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.MappingConstants;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* 用户信息转换器
|
||||
*
|
||||
*/
|
||||
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface SysOssVoConvert extends BaseMapper<SysOssVo, RemoteFile> {
|
||||
|
||||
@Mapping(target = "name", source = "fileName")
|
||||
RemoteFile convert(SysOssVo sysOssVo);
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package cn.aixunkeji.resource.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息盒子视图对象
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
public class SysMessageBoxVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private List<SysMessageVo> systemList = new ArrayList<>();
|
||||
|
||||
private List<SysMessageVo> noticeList = new ArrayList<>();
|
||||
|
||||
private List<SysMessageVo> workflowList = new ArrayList<>();
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package cn.aixunkeji.resource.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 消息记录视图对象
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
public class SysMessageVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long messageId;
|
||||
|
||||
private String category;
|
||||
|
||||
private String type;
|
||||
|
||||
private String source;
|
||||
|
||||
private String title;
|
||||
|
||||
private String message;
|
||||
|
||||
private String content;
|
||||
|
||||
private Object data;
|
||||
|
||||
private String path;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package cn.aixunkeji.resource.domain.vo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import cn.aixunkeji.resource.domain.SysOssConfig;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/**
|
||||
* 对象存储配置视图对象 sys_oss_config
|
||||
*
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Data
|
||||
@AutoMapper(target = SysOssConfig.class)
|
||||
public class SysOssConfigVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
private Long ossConfigId;
|
||||
|
||||
/**
|
||||
* 配置key
|
||||
*/
|
||||
private String configKey;
|
||||
|
||||
/**
|
||||
* accessKey
|
||||
*/
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
private String prefix;
|
||||
|
||||
/**
|
||||
* 访问站点
|
||||
*/
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String domainUrl;
|
||||
|
||||
/**
|
||||
* 是否https(Y=是,N=否)
|
||||
*/
|
||||
private String isHttps;
|
||||
|
||||
/**
|
||||
* 域
|
||||
*/
|
||||
private String region;
|
||||
|
||||
/**
|
||||
* 是否默认(Y=是,N=否)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 桶权限类型(0private 1public 2custom)
|
||||
*/
|
||||
private String accessPolicy;
|
||||
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package cn.aixunkeji.resource.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 上传对象信息
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
public class SysOssUploadVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
private String ossId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package cn.aixunkeji.resource.domain.vo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import cn.aixunkeji.common.translation.annotation.Translation;
|
||||
import cn.aixunkeji.common.translation.constant.TransConstant;
|
||||
import cn.aixunkeji.resource.domain.SysOss;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* OSS对象存储视图对象 sys_oss
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
@AutoMapper(target = SysOss.class)
|
||||
public class SysOssVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 上传人
|
||||
*/
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 上传人名称
|
||||
*/
|
||||
@Translation(type = TransConstant.USER_ID_TO_NAME, mapper = "createBy")
|
||||
private String createByName;
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package cn.aixunkeji.resource.dubbo;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.core.utils.MapstructUtils;
|
||||
import cn.aixunkeji.common.core.utils.StringUtils;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.oss.client.OssClient;
|
||||
import cn.aixunkeji.common.oss.factory.OssFactory;
|
||||
import cn.aixunkeji.common.oss.model.PutObjectResult;
|
||||
import cn.aixunkeji.resource.api.RemoteFileService;
|
||||
import cn.aixunkeji.resource.api.domain.RemoteFile;
|
||||
import cn.aixunkeji.resource.domain.SysOssExt;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssVo;
|
||||
import cn.aixunkeji.resource.service.ISysOssService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件请求处理
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@DubboService
|
||||
public class RemoteFileServiceImpl implements RemoteFileService {
|
||||
|
||||
private final ISysOssService sysOssService;
|
||||
|
||||
/**
|
||||
* 通过ossId查询对应的url
|
||||
*
|
||||
* @param ossIds ossId串逗号分隔
|
||||
* @return url串逗号分隔
|
||||
*/
|
||||
@Override
|
||||
public String selectUrlByIds(String ossIds) {
|
||||
return sysOssService.selectUrlByIds(ossIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过ossId查询列表
|
||||
*
|
||||
* @param ossIds ossId串逗号分隔
|
||||
* @return 列表
|
||||
*/
|
||||
@Override
|
||||
public List<RemoteFile> selectByIds(String ossIds) {
|
||||
List<SysOssVo> sysOssVos = sysOssService.listByIds(StringUtils.splitTo(ossIds, Convert::toLong));
|
||||
return MapstructUtils.convert(sysOssVos, RemoteFile.class);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.aixunkeji.resource.dubbo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.mail.core.MailBuilder;
|
||||
import cn.aixunkeji.resource.api.RemoteMailService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 邮件服务
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@DubboService
|
||||
@ConditionalOnProperty(value = "mail.enabled", havingValue = "true")
|
||||
public class RemoteMailServiceImpl implements RemoteMailService {
|
||||
|
||||
/**
|
||||
* 发送邮件
|
||||
*
|
||||
* @param to 接收人
|
||||
* @param subject 标题
|
||||
* @param text 内容
|
||||
*/
|
||||
@Override
|
||||
public void send(String to, String subject, String text) throws ServiceException {
|
||||
MailBuilder.of().to(to).subject(subject).text(text).send();
|
||||
}
|
||||
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package cn.aixunkeji.resource.dubbo;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import cn.aixunkeji.common.core.enums.PushSourceEnum;
|
||||
import cn.aixunkeji.common.core.enums.PushTypeEnum;
|
||||
import cn.aixunkeji.common.push.dto.PushPayloadDTO;
|
||||
import cn.aixunkeji.common.push.helper.PushHelper;
|
||||
import cn.aixunkeji.resource.api.RemoteMessageService;
|
||||
import cn.aixunkeji.resource.api.domain.RemotePushPayLoad;
|
||||
import cn.aixunkeji.resource.service.ISysMessageService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息服务
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@DubboService
|
||||
public class RemoteMessageServiceImpl implements RemoteMessageService {
|
||||
|
||||
private final ISysMessageService sysMessageService;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.resource.service.impl.WorkflowAlertMailboxService workflowMailbox;
|
||||
|
||||
@Override public MailboxReceipt storeWorkflowAlert(WorkflowAlertMessage command) {
|
||||
return workflowMailbox.store(command);
|
||||
}
|
||||
|
||||
@Override public MailboxReceipt readWorkflowAlert(WorkflowAlertMessage command) {
|
||||
return workflowMailbox.read(command);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*
|
||||
* @param userIds 用户ID列表
|
||||
* @param message 消息文本
|
||||
*/
|
||||
@Override
|
||||
public void publishMessage(List<Long> userIds, String message) {
|
||||
publishMessagePayload(userIds, RemotePushPayLoad.of(PushTypeEnum.MESSAGE, PushSourceEnum.BACKEND, message, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishMessagePayload(List<Long> userIds, RemotePushPayLoad payload) {
|
||||
PushPayloadDTO pushPayload = BeanUtil.copyProperties(payload, PushPayloadDTO.class);
|
||||
PushHelper.publishMessage(userIds, sysMessageService.storeUsers(userIds, pushPayload));
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布订阅的消息(群发)
|
||||
*
|
||||
* @param message 消息内容
|
||||
*/
|
||||
@Override
|
||||
public void publishAll(String message) {
|
||||
publishAllPayload(RemotePushPayLoad.of(PushTypeEnum.MESSAGE, PushSourceEnum.BACKEND, message, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishAllPayload(RemotePushPayLoad payload) {
|
||||
PushPayloadDTO pushPayload = BeanUtil.copyProperties(payload, PushPayloadDTO.class);
|
||||
PushHelper.publishAll(sysMessageService.storeAll(pushPayload));
|
||||
}
|
||||
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
package cn.aixunkeji.resource.dubbo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import cn.aixunkeji.resource.api.RemoteSmsService;
|
||||
import cn.aixunkeji.resource.api.domain.RemoteSms;
|
||||
import org.dromara.sms4j.api.SmsBlend;
|
||||
import org.dromara.sms4j.api.entity.SmsResponse;
|
||||
import org.dromara.sms4j.core.factory.SmsFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 短信服务
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@DubboService
|
||||
@ConditionalOnProperty(value = "sms.enabled", havingValue = "true")
|
||||
public class RemoteSmsServiceImpl implements RemoteSmsService {
|
||||
|
||||
/**
|
||||
* 获取特定供应商类型的 SmsBlend 实例
|
||||
*
|
||||
* @return SmsBlend 实例,代表指定供应商类型
|
||||
*/
|
||||
private SmsBlend getSmsBlend() {
|
||||
// 自动获取一个短信服务商
|
||||
// return SmsFactory.getSmsBlend();
|
||||
// 可自定义厂商配置获取规则 例如根据租户获取 或 负载均衡多个厂商等
|
||||
return SmsFactory.getSmsBlend("config1");
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据给定的 SmsResponse 对象创建并返回一个 RemoteSms 对象,封装短信发送的响应信息
|
||||
*
|
||||
* @param smsResponse 短信发送的响应信息
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
private RemoteSms getRemoteSms(SmsResponse smsResponse) {
|
||||
// 创建一个 RemoteSms 对象,封装响应信息
|
||||
RemoteSms sms = new RemoteSms();
|
||||
sms.setSuccess(smsResponse.isSuccess());
|
||||
sms.setResponse(smsResponse.getData().toString());
|
||||
sms.setConfigId(smsResponse.getConfigId());
|
||||
return sms;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:发送简单文本短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param message 短信内容
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms sendMessage(String phone, String message) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().sendMessage(phone, message);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:发送固定消息模板多模板参数短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms sendMessage(String phone, LinkedHashMap<String, String> messages) {
|
||||
SmsResponse smsResponse = getSmsBlend().sendMessage(phone, messages);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:发送带参数的短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms sendMessage(String phone, String templateId, LinkedHashMap<String, String> messages) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().sendMessage(phone, templateId, messages);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:群发简单文本短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param message 短信内容
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms messageTexting(List<String> phones, String message) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().massTexting(phones, message);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:群发带参数的短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms messageTexting(List<String> phones, String templateId, LinkedHashMap<String, String> messages) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().massTexting(phones, templateId, messages);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步方法:发送简单文本短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param message 短信内容
|
||||
*/
|
||||
@Override
|
||||
public void sendMessageAsync(String phone, String message) {
|
||||
getSmsBlend().sendMessageAsync(phone, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步方法:发送带参数的短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
*/
|
||||
@Override
|
||||
public void sendMessageAsync(String phone, String templateId, LinkedHashMap<String, String> messages) {
|
||||
getSmsBlend().sendMessageAsync(phone, templateId, messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟发送简单文本短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param message 短信内容
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessage(String phone, String message, Long delayedTime) {
|
||||
getSmsBlend().delayedMessage(phone, message, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟发送带参数的短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessage(String phone, String templateId, LinkedHashMap<String, String> messages, Long delayedTime) {
|
||||
getSmsBlend().delayedMessage(phone, templateId, messages, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟群发简单文本短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param message 短信内容
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessageTexting(List<String> phones, String message, Long delayedTime) {
|
||||
getSmsBlend().delayMassTexting(phones, message, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟批量发送带参数的短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessageTexting(List<String> phones, String templateId, LinkedHashMap<String, String> messages, Long delayedTime) {
|
||||
getSmsBlend().delayMassTexting(phones, templateId, messages, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加入黑名单
|
||||
*
|
||||
* @param phone 手机号
|
||||
*/
|
||||
@Override
|
||||
public void addBlacklist(String phone) {
|
||||
getSmsBlend().joinInBlacklist(phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加入黑名单
|
||||
*
|
||||
* @param phones 手机号列表
|
||||
*/
|
||||
@Override
|
||||
public void addBlacklist(List<String> phones) {
|
||||
getSmsBlend().batchJoinBlacklist(phones);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除黑名单
|
||||
*
|
||||
* @param phone 手机号
|
||||
*/
|
||||
@Override
|
||||
public void removeBlacklist(String phone) {
|
||||
getSmsBlend().removeFromBlacklist(phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除黑名单
|
||||
*
|
||||
* @param phones 手机号
|
||||
*/
|
||||
@Override
|
||||
public void removeBlacklist(List<String> phones) {
|
||||
getSmsBlend().batchRemovalFromBlacklist(phones);
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package cn.aixunkeji.resource.event;
|
||||
|
||||
/**
|
||||
* OSS 配置变更事件。
|
||||
*
|
||||
* @param configKey 当前配置 key
|
||||
* @param oldConfigKey 变更前配置 key
|
||||
* @param configJson 当前配置 JSON,为空表示清理缓存
|
||||
* @param defaultConfig 是否设置为默认配置
|
||||
*/
|
||||
public record OssConfigChangeEvent(
|
||||
String configKey,
|
||||
String oldConfigKey,
|
||||
String configJson,
|
||||
boolean defaultConfig
|
||||
) {
|
||||
|
||||
/**
|
||||
* 创建保存 OSS 配置后的变更事件。
|
||||
*
|
||||
* @param configKey 当前配置 key
|
||||
* @param oldConfigKey 变更前配置 key
|
||||
* @param configJson 当前配置 JSON
|
||||
* @return OSS 配置变更事件
|
||||
*/
|
||||
public static OssConfigChangeEvent save(String configKey, String oldConfigKey, String configJson) {
|
||||
return new OssConfigChangeEvent(configKey, oldConfigKey, configJson, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建删除 OSS 配置后的变更事件。
|
||||
*
|
||||
* @param configKey 配置 key
|
||||
* @return OSS 配置变更事件
|
||||
*/
|
||||
public static OssConfigChangeEvent remove(String configKey) {
|
||||
return new OssConfigChangeEvent(configKey, null, null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建切换默认 OSS 配置后的变更事件。
|
||||
*
|
||||
* @param configKey 默认配置 key
|
||||
* @return OSS 配置变更事件
|
||||
*/
|
||||
public static OssConfigChangeEvent useDefault(String configKey) {
|
||||
return new OssConfigChangeEvent(configKey, null, null, true);
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package cn.aixunkeji.resource.listener;
|
||||
|
||||
import cn.aixunkeji.common.core.constant.CacheNames;
|
||||
import cn.aixunkeji.common.core.utils.StringUtils;
|
||||
import cn.aixunkeji.common.oss.constant.OssConstant;
|
||||
import cn.aixunkeji.common.oss.factory.OssFactory;
|
||||
import cn.aixunkeji.common.redis.utils.CacheUtils;
|
||||
import cn.aixunkeji.common.redis.utils.RedisUtils;
|
||||
import cn.aixunkeji.resource.event.OssConfigChangeEvent;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
/**
|
||||
* OSS 配置变更监听器。
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class OssConfigChangeListener {
|
||||
|
||||
/**
|
||||
* 数据提交后同步刷新 OSS 配置缓存与客户端实例。
|
||||
*
|
||||
* @param event OSS 配置变更事件
|
||||
*/
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
|
||||
public void refreshOssConfig(OssConfigChangeEvent event) {
|
||||
if (event.defaultConfig()) {
|
||||
RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, event.configKey());
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isNotBlank(event.oldConfigKey()) && !StringUtils.equals(event.oldConfigKey(), event.configKey())) {
|
||||
CacheUtils.evict(CacheNames.SYS_OSS_CONFIG, event.oldConfigKey());
|
||||
OssFactory.remove(event.oldConfigKey());
|
||||
}
|
||||
if (StringUtils.isBlank(event.configKey())) {
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isBlank(event.configJson())) {
|
||||
CacheUtils.evict(CacheNames.SYS_OSS_CONFIG, event.configKey());
|
||||
} else {
|
||||
CacheUtils.put(CacheNames.SYS_OSS_CONFIG, event.configKey(), event.configJson());
|
||||
}
|
||||
OssFactory.remove(event.configKey());
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package cn.aixunkeji.resource.mapper;
|
||||
|
||||
import cn.aixunkeji.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import cn.aixunkeji.resource.domain.SysMessage;
|
||||
import cn.aixunkeji.resource.domain.vo.SysMessageVo;
|
||||
|
||||
/**
|
||||
* 消息记录Mapper接口
|
||||
*
|
||||
*/
|
||||
public interface SysMessageMapper extends BaseMapperPlus<SysMessage, SysMessageVo> {
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cn.aixunkeji.resource.mapper;
|
||||
|
||||
|
||||
import cn.aixunkeji.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import cn.aixunkeji.resource.domain.SysOssConfig;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssConfigVo;
|
||||
|
||||
/**
|
||||
* 对象存储配置Mapper接口
|
||||
*
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
public interface SysOssConfigMapper extends BaseMapperPlus<SysOssConfig, SysOssConfigVo> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package cn.aixunkeji.resource.mapper;
|
||||
|
||||
import cn.aixunkeji.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import cn.aixunkeji.resource.domain.SysOss;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssVo;
|
||||
|
||||
/**
|
||||
* 文件上传 数据层
|
||||
*
|
||||
*/
|
||||
public interface SysOssMapper extends BaseMapperPlus<SysOss, SysOssVo> {
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.aixunkeji.resource.runner;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import cn.aixunkeji.resource.service.ISysOssConfigService;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 初始化 system 模块对应业务数据
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
public class ResourceApplicationRunner implements ApplicationRunner {
|
||||
|
||||
private final ISysOssConfigService ossConfigService;
|
||||
|
||||
/**
|
||||
* 应用启动后初始化 OSS 配置缓存。
|
||||
*
|
||||
* @param args 启动参数
|
||||
*/
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
ossConfigService.init();
|
||||
log.info("初始化OSS配置成功");
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package cn.aixunkeji.resource.service;
|
||||
|
||||
import cn.aixunkeji.common.push.dto.PushPayloadDTO;
|
||||
import cn.aixunkeji.resource.domain.vo.SysMessageBoxVo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息记录服务接口
|
||||
*
|
||||
*/
|
||||
public interface ISysMessageService {
|
||||
|
||||
/**
|
||||
* 查询当前用户消息盒子数据
|
||||
* 按系统消息、通知公告、工作流消息分类返回
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 消息盒子数据
|
||||
*/
|
||||
SysMessageBoxVo queryMessageBox(Long userId);
|
||||
|
||||
/**
|
||||
* 存储全局广播消息到数据库
|
||||
*
|
||||
* @param payload 消息推送体
|
||||
* @return 回填消息ID后的消息体
|
||||
*/
|
||||
PushPayloadDTO storeAll(PushPayloadDTO payload);
|
||||
|
||||
/**
|
||||
* 存储指定用户消息到数据库
|
||||
*
|
||||
* @param userIds 用户ID集合
|
||||
* @param payload 消息推送体
|
||||
* @return 回填消息ID后的消息体
|
||||
*/
|
||||
PushPayloadDTO storeUsers(List<Long> userIds, PushPayloadDTO payload);
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package cn.aixunkeji.resource.service;
|
||||
|
||||
|
||||
import cn.aixunkeji.common.core.domain.PageResult;
|
||||
import cn.aixunkeji.common.mybatis.core.page.PageQuery;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssConfigBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssConfigVo;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 对象存储配置Service接口
|
||||
*
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
public interface ISysOssConfigService {
|
||||
|
||||
/**
|
||||
* 初始化OSS配置
|
||||
*/
|
||||
void init();
|
||||
|
||||
/**
|
||||
* 查询单个
|
||||
*/
|
||||
SysOssConfigVo queryById(Long ossConfigId);
|
||||
|
||||
/**
|
||||
* 查询列表
|
||||
*/
|
||||
PageResult<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery);
|
||||
|
||||
|
||||
/**
|
||||
* 根据新增业务对象插入对象存储配置
|
||||
*
|
||||
* @param bo 对象存储配置新增业务对象
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean insertByBo(SysOssConfigBo bo);
|
||||
|
||||
/**
|
||||
* 根据编辑业务对象修改对象存储配置
|
||||
*
|
||||
* @param bo 对象存储配置编辑业务对象
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean updateByBo(SysOssConfigBo bo);
|
||||
|
||||
/**
|
||||
* 校验并删除数据
|
||||
*
|
||||
* @param ids 主键集合
|
||||
* @param isValid 是否校验,true-删除前校验,false-不校验
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
|
||||
/**
|
||||
* 启用停用状态
|
||||
*/
|
||||
int updateOssConfigStatus(SysOssConfigBo bo);
|
||||
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package cn.aixunkeji.resource.service;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.PageResult;
|
||||
import cn.aixunkeji.common.mybatis.core.page.PageQuery;
|
||||
import cn.aixunkeji.resource.domain.SysOssExt;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssVo;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件上传 服务层
|
||||
*
|
||||
*/
|
||||
public interface ISysOssService {
|
||||
|
||||
/**
|
||||
* 查询OSS对象存储列表
|
||||
*
|
||||
* @param sysOss OSS对象存储分页查询对象
|
||||
* @param pageQuery 分页查询实体类
|
||||
* @return 结果
|
||||
*/
|
||||
PageResult<SysOssVo> queryPageList(SysOssBo sysOss, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应的 SysOssVo 列表
|
||||
*
|
||||
* @param ossIds 一组文件在数据库中的唯一标识集合
|
||||
* @return 包含 SysOssVo 对象的列表
|
||||
*/
|
||||
List<SysOssVo> listByIds(Collection<Long> ossIds);
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应文件的 URL 列表
|
||||
*
|
||||
* @param ossIds 以逗号分隔的 ossId 字符串
|
||||
* @return 以逗号分隔的文件 URL 字符串
|
||||
*/
|
||||
String selectUrlByIds(String ossIds);
|
||||
|
||||
/**
|
||||
* 根据 ossId 从缓存或数据库中获取 SysOssVo 对象
|
||||
*
|
||||
* @param ossId 文件在数据库中的唯一标识
|
||||
* @return SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
SysOssVo getById(Long ossId);
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的 MultipartFile 对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
default SysOssVo upload(MultipartFile file) {
|
||||
return upload(file, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的 MultipartFile 对象
|
||||
* @param ossExt 扩展信息
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
SysOssVo upload(MultipartFile file, SysOssExt ossExt);
|
||||
|
||||
/**
|
||||
* 上传文件到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的文件对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
default SysOssVo upload(File file) {
|
||||
return upload(file, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的文件对象
|
||||
* @param ossExt 扩展信息
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
SysOssVo upload(File file, SysOssExt ossExt);
|
||||
|
||||
/**
|
||||
* 新增OSS对象存储
|
||||
*
|
||||
* @param bo SysOssBo 对象,包含待插入的数据
|
||||
* @return 插入操作是否成功的布尔值
|
||||
*/
|
||||
Boolean insertByBo(SysOssBo bo);
|
||||
|
||||
/**
|
||||
* 文件下载方法,支持一次性下载完整文件
|
||||
*
|
||||
* @param ossId OSS对象ID
|
||||
*/
|
||||
ResponseEntity<byte[]> download(Long ossId);
|
||||
|
||||
/**
|
||||
* 删除OSS对象存储
|
||||
*
|
||||
* @param ids OSS对象ID串
|
||||
* @param isValid 判断是否需要校验
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
}
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
package cn.aixunkeji.resource.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import cn.aixunkeji.common.core.enums.PushSourceEnum;
|
||||
import cn.aixunkeji.common.core.enums.PushTypeEnum;
|
||||
import cn.aixunkeji.common.core.utils.StringUtils;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.common.push.dto.PushPayloadDTO;
|
||||
import cn.aixunkeji.resource.domain.SysMessage;
|
||||
import cn.aixunkeji.resource.domain.vo.SysMessageBoxVo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysMessageVo;
|
||||
import cn.aixunkeji.resource.mapper.SysMessageMapper;
|
||||
import cn.aixunkeji.resource.service.ISysMessageService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 消息记录服务实现
|
||||
*
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SysMessageServiceImpl implements ISysMessageService {
|
||||
|
||||
/**
|
||||
* 全局广播用户标识(所有用户可见)
|
||||
*/
|
||||
private static final String GLOBAL_USER_IDS = "0";
|
||||
|
||||
/**
|
||||
* 消息分类:系统消息
|
||||
*/
|
||||
private static final String CATEGORY_SYSTEM = "system";
|
||||
|
||||
/**
|
||||
* 消息分类:通知公告
|
||||
*/
|
||||
private static final String CATEGORY_NOTICE = "notice";
|
||||
|
||||
/**
|
||||
* 消息分类:工作流
|
||||
*/
|
||||
private static final String CATEGORY_WORKFLOW = "workflow";
|
||||
|
||||
/**
|
||||
* 消息盒子每页展示最大条数
|
||||
*/
|
||||
private static final int BOX_LIMIT = 100;
|
||||
|
||||
/**
|
||||
* 消息盒子展示消息天数(仅展示30天内)
|
||||
*/
|
||||
private static final long BOX_DAYS = 30L;
|
||||
|
||||
private final SysMessageMapper messageMapper;
|
||||
|
||||
/**
|
||||
* 查询当前用户消息盒子数据
|
||||
* 按系统消息、通知公告、工作流消息分类返回
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 分类消息盒子数据
|
||||
*/
|
||||
@Override
|
||||
public SysMessageBoxVo queryMessageBox(Long userId) {
|
||||
SysMessageBoxVo box = new SysMessageBoxVo();
|
||||
box.setSystemList(selectMessageList(CATEGORY_SYSTEM, userId));
|
||||
box.setNoticeList(selectMessageList(CATEGORY_NOTICE, userId));
|
||||
box.setWorkflowList(selectMessageList(CATEGORY_WORKFLOW, userId));
|
||||
return box;
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储全局广播消息到数据库
|
||||
*
|
||||
* @param payload 消息推送体
|
||||
* @return 回填消息ID后的消息体
|
||||
*/
|
||||
@Override
|
||||
public PushPayloadDTO storeAll(PushPayloadDTO payload) {
|
||||
return storeMessage(null, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储指定用户消息到数据库
|
||||
*
|
||||
* @param userIds 用户ID集合
|
||||
* @param payload 消息推送体
|
||||
* @return 回填消息ID后的消息体
|
||||
*/
|
||||
@Override
|
||||
public PushPayloadDTO storeUsers(List<Long> userIds, PushPayloadDTO payload) {
|
||||
return storeMessage(userIds, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一消息存储逻辑
|
||||
* 判断是否需要存入消息盒子,需要则插入数据库
|
||||
*
|
||||
* @param userIds 用户ID集合(为null则全局广播)
|
||||
* @param payload 消息推送体
|
||||
* @return 回填消息ID后的消息体
|
||||
*/
|
||||
private PushPayloadDTO storeMessage(List<Long> userIds, PushPayloadDTO payload) {
|
||||
if (!supportsMessageBox(payload)) {
|
||||
return payload;
|
||||
}
|
||||
SysMessage message = buildMessage(userIds, payload);
|
||||
messageMapper.insert(message);
|
||||
payload.setMessageId(message.getMessageId());
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据分类和用户ID查询消息列表
|
||||
* 仅查询30天内、最多100条、按时间倒序
|
||||
*
|
||||
* @param category 消息分类
|
||||
* @param userId 用户ID
|
||||
* @return 消息VO列表
|
||||
*/
|
||||
private List<SysMessageVo> selectMessageList(String category, Long userId) {
|
||||
List<SysMessage> list = messageMapper.lambda()
|
||||
.eq(SysMessage::getCategory, category)
|
||||
.ge(SysMessage::getCreateTime, LocalDateTime.now().minusDays(BOX_DAYS))
|
||||
.and(wrapper ->
|
||||
wrapper.eq(SysMessage::getSendUserIds, GLOBAL_USER_IDS)
|
||||
.or()
|
||||
.findInSet(userId, SysMessage::getSendUserIds)
|
||||
)
|
||||
.orderByDesc(SysMessage::getCreateTime, SysMessage::getMessageId)
|
||||
.list(new Page<>(1, BOX_LIMIT, false));
|
||||
return list.stream().map(this::buildVo).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建消息实体(用于数据库存储)
|
||||
*
|
||||
* @param userIds 接收用户ID集合
|
||||
* @param payload 消息推送体
|
||||
* @return 系统消息实体
|
||||
*/
|
||||
private SysMessage buildMessage(List<Long> userIds, PushPayloadDTO payload) {
|
||||
SysMessage message = new SysMessage();
|
||||
message.setMessageId(payload.getMessageId() == null ? IdGeneratorUtil.nextLongId() : payload.getMessageId());
|
||||
message.setCategory(resolveCategory(payload));
|
||||
message.setType(payload.getType());
|
||||
message.setSource(payload.getSource());
|
||||
message.setTitle(resolveTitle(payload));
|
||||
message.setMessage(payload.getMessage());
|
||||
message.setContent(resolveContent(payload));
|
||||
message.setDataJson(JsonUtils.toJsonString(payload.getData()));
|
||||
message.setPath(payload.getPath());
|
||||
message.setSendUserIds(CollUtil.isEmpty(userIds) ? GLOBAL_USER_IDS : StringUtils.joinComma(userIds));
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息实体转换为展示VO
|
||||
*
|
||||
* @param entity 消息实体
|
||||
* @return 消息展示VO
|
||||
*/
|
||||
private SysMessageVo buildVo(SysMessage entity) {
|
||||
SysMessageVo vo = new SysMessageVo();
|
||||
vo.setMessageId(entity.getMessageId());
|
||||
vo.setCategory(entity.getCategory());
|
||||
vo.setType(entity.getType());
|
||||
vo.setSource(entity.getSource());
|
||||
vo.setTitle(entity.getTitle());
|
||||
vo.setMessage(entity.getMessage());
|
||||
vo.setContent(entity.getContent());
|
||||
vo.setPath(entity.getPath());
|
||||
vo.setCreateTime(entity.getCreateTime());
|
||||
vo.setData(parseData(entity.getDataJson()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断消息是否需要存入消息盒子
|
||||
* 仅系统消息、通知消息需要存入
|
||||
*
|
||||
* @param payload 消息推送体
|
||||
* @return 是否支持存入消息盒子
|
||||
*/
|
||||
private boolean supportsMessageBox(PushPayloadDTO payload) {
|
||||
if (payload == null) {
|
||||
return false;
|
||||
}
|
||||
if (StringUtils.equalsAny(payload.getType(), PushTypeEnum.MESSAGE.getType(), PushTypeEnum.NOTICE.getType())) {
|
||||
return !StringUtils.equalsAny(payload.getType(), PushTypeEnum.LLM.getType())
|
||||
&& !StringUtils.equalsAny(payload.getSource(), PushSourceEnum.LLM.getSource());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据消息类型/来源自动解析消息分类
|
||||
*
|
||||
* @param payload 消息推送体
|
||||
* @return 消息分类(system/notice/workflow)
|
||||
*/
|
||||
private String resolveCategory(PushPayloadDTO payload) {
|
||||
if (StringUtils.equalsAny(payload.getType(), PushTypeEnum.NOTICE.getType())
|
||||
|| StringUtils.equalsAny(payload.getSource(), PushSourceEnum.NOTICE.getSource())) {
|
||||
return CATEGORY_NOTICE;
|
||||
}
|
||||
if (StringUtils.equalsAny(payload.getSource(), PushSourceEnum.WORKFLOW.getSource())) {
|
||||
return CATEGORY_WORKFLOW;
|
||||
}
|
||||
return CATEGORY_SYSTEM;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据消息分类自动生成消息标题
|
||||
*
|
||||
* @param payload 消息推送体
|
||||
* @return 消息标题
|
||||
*/
|
||||
private String resolveTitle(PushPayloadDTO payload) {
|
||||
return switch (resolveCategory(payload)) {
|
||||
case CATEGORY_NOTICE -> "通知公告消息";
|
||||
case CATEGORY_WORKFLOW -> "工作流消息";
|
||||
default -> "系统消息";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析消息内容(从data中提取noticeContent)
|
||||
*
|
||||
* @param payload 消息推送体
|
||||
* @return 消息内容
|
||||
*/
|
||||
private String resolveContent(PushPayloadDTO payload) {
|
||||
Object data = payload.getData();
|
||||
if (data instanceof Map<?, ?> map) {
|
||||
return Convert.toStr(map.get("noticeContent"));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析JSON数据字符串为对象
|
||||
*
|
||||
* @param dataJson JSON字符串
|
||||
* @return 解析后对象
|
||||
*/
|
||||
private Object parseData(String dataJson) {
|
||||
if (StringUtils.isBlank(dataJson)) {
|
||||
return null;
|
||||
}
|
||||
return JsonUtils.parseObject(dataJson, Object.class);
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package cn.aixunkeji.resource.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import cn.aixunkeji.common.core.constant.CacheNames;
|
||||
import cn.aixunkeji.common.core.constant.SystemConstants;
|
||||
import cn.aixunkeji.common.core.domain.PageResult;
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.core.utils.MapstructUtils;
|
||||
import cn.aixunkeji.common.core.utils.ObjectUtils;
|
||||
import cn.aixunkeji.common.core.utils.SpringUtils;
|
||||
import cn.aixunkeji.common.core.utils.StringUtils;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.mybatis.core.page.PageQuery;
|
||||
import cn.aixunkeji.common.mybatis.core.query.QueryBuilder;
|
||||
import cn.aixunkeji.common.oss.constant.OssConstant;
|
||||
import cn.aixunkeji.common.redis.utils.CacheUtils;
|
||||
import cn.aixunkeji.common.redis.utils.RedisUtils;
|
||||
import cn.aixunkeji.resource.domain.SysOssConfig;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssConfigBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssConfigVo;
|
||||
import cn.aixunkeji.resource.event.OssConfigChangeEvent;
|
||||
import cn.aixunkeji.resource.mapper.SysOssConfigMapper;
|
||||
import cn.aixunkeji.resource.service.ISysOssConfigService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 对象存储配置Service业务层处理
|
||||
*
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SysOssConfigServiceImpl implements ISysOssConfigService {
|
||||
|
||||
private final SysOssConfigMapper ossConfigMapper;
|
||||
|
||||
/**
|
||||
* 项目启动时,初始化参数到缓存,加载配置类
|
||||
*/
|
||||
@Override
|
||||
public void init() {
|
||||
List<SysOssConfig> list = ossConfigMapper.selectList();
|
||||
// 加载OSS初始化配置
|
||||
for (SysOssConfig config : list) {
|
||||
String configKey = config.getConfigKey();
|
||||
if (SystemConstants.YES.equals(config.getStatus())) {
|
||||
RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, configKey);
|
||||
}
|
||||
CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SysOssConfigVo queryById(Long ossConfigId) {
|
||||
return ossConfigMapper.selectVoById(ossConfigId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResult<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery) {
|
||||
LambdaQueryWrapper<SysOssConfig> lqw = buildQueryWrapper(bo);
|
||||
Page<SysOssConfigVo> result = ossConfigMapper.selectVoPage(pageQuery.build(), lqw);
|
||||
return PageResult.build(result.getRecords(), result.getTotal());
|
||||
}
|
||||
|
||||
|
||||
private LambdaQueryWrapper<SysOssConfig> buildQueryWrapper(SysOssConfigBo bo) {
|
||||
return QueryBuilder.lambda(SysOssConfig.class)
|
||||
.eqIfText(SysOssConfig::getConfigKey, bo.getConfigKey())
|
||||
.likeIfText(SysOssConfig::getBucketName, bo.getBucketName())
|
||||
.eqIfText(SysOssConfig::getStatus, bo.getStatus())
|
||||
.orderByAsc(SysOssConfig::getOssConfigId)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean insertByBo(SysOssConfigBo bo) {
|
||||
SysOssConfig config = MapstructUtils.convert(bo, SysOssConfig.class);
|
||||
validEntityBeforeSave(config);
|
||||
boolean flag = ossConfigMapper.insert(config) > 0;
|
||||
if (flag) {
|
||||
// 从数据库查询完整的数据做缓存
|
||||
config = ossConfigMapper.selectById(config.getOssConfigId());
|
||||
publishOssConfigSaved(config, null);
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateByBo(SysOssConfigBo bo) {
|
||||
SysOssConfig config = MapstructUtils.convert(bo, SysOssConfig.class);
|
||||
validEntityBeforeSave(config);
|
||||
SysOssConfig oldConfig = ossConfigMapper.selectById(config.getOssConfigId());
|
||||
boolean flag = ossConfigMapper.lambda()
|
||||
.set(ObjectUtil.isNull(config.getPrefix()), SysOssConfig::getPrefix, "")
|
||||
.set(ObjectUtil.isNull(config.getRegion()), SysOssConfig::getRegion, "")
|
||||
.set(ObjectUtil.isNull(config.getExt1()), SysOssConfig::getExt1, "")
|
||||
.set(ObjectUtil.isNull(config.getRemark()), SysOssConfig::getRemark, "")
|
||||
.eq(SysOssConfig::getOssConfigId, config.getOssConfigId())
|
||||
.update(config);
|
||||
if (flag) {
|
||||
// 从数据库查询完整的数据做缓存
|
||||
config = ossConfigMapper.selectById(config.getOssConfigId());
|
||||
publishOssConfigSaved(config, ObjectUtils.notNullGetter(oldConfig, SysOssConfig::getConfigKey));
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存前的数据校验
|
||||
*/
|
||||
private void validEntityBeforeSave(SysOssConfig entity) {
|
||||
if (StringUtils.isNotEmpty(entity.getConfigKey()) && !checkConfigKeyUnique(entity)) {
|
||||
throw new ServiceException("操作配置'{}'失败, 配置key已存在!", entity.getConfigKey());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
|
||||
if (isValid) {
|
||||
if (CollUtil.containsAny(ids, OssConstant.SYSTEM_DATA_IDS)) {
|
||||
throw new ServiceException("系统内置, 不可删除!");
|
||||
}
|
||||
}
|
||||
List<SysOssConfig> list = CollUtil.newArrayList();
|
||||
for (Long configId : ids) {
|
||||
SysOssConfig config = ossConfigMapper.selectById(configId);
|
||||
if (ObjectUtil.isNotNull(config)) {
|
||||
list.add(config);
|
||||
}
|
||||
}
|
||||
boolean flag = ossConfigMapper.deleteByIds(ids) > 0;
|
||||
if (flag) {
|
||||
list.forEach(sysOssConfig ->
|
||||
SpringUtils.context().publishEvent(OssConfigChangeEvent.remove(sysOssConfig.getConfigKey())));
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断configKey是否唯一
|
||||
*/
|
||||
private boolean checkConfigKeyUnique(SysOssConfig sysOssConfig) {
|
||||
long ossConfigId = ObjectUtils.notNull(sysOssConfig.getOssConfigId(), -1L);
|
||||
SysOssConfig info = ossConfigMapper.lambda()
|
||||
.select(SysOssConfig::getOssConfigId, SysOssConfig::getConfigKey)
|
||||
.eq(SysOssConfig::getConfigKey, sysOssConfig.getConfigKey())
|
||||
.one();
|
||||
return ObjectUtil.isNull(info) || ObjectUtil.equals(info.getOssConfigId(), ossConfigId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用禁用状态
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateOssConfigStatus(SysOssConfigBo bo) {
|
||||
SysOssConfig sysOssConfig = MapstructUtils.convert(bo, SysOssConfig.class);
|
||||
int row = ossConfigMapper.lambda().set(SysOssConfig::getStatus, SystemConstants.NO).updateCount();
|
||||
row += ossConfigMapper.updateById(sysOssConfig);
|
||||
if (row > 0) {
|
||||
SpringUtils.context().publishEvent(OssConfigChangeEvent.useDefault(sysOssConfig.getConfigKey()));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布 OSS 配置保存事件。
|
||||
*
|
||||
* @param config 当前配置
|
||||
* @param oldConfigKey 变更前配置 key
|
||||
*/
|
||||
private void publishOssConfigSaved(SysOssConfig config, String oldConfigKey) {
|
||||
SpringUtils.context().publishEvent(OssConfigChangeEvent.save(
|
||||
config.getConfigKey(),
|
||||
oldConfigKey,
|
||||
JsonUtils.toJsonString(config)
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
package cn.aixunkeji.resource.service.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import cn.aixunkeji.common.core.domain.PageResult;
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.core.utils.*;
|
||||
import cn.aixunkeji.common.core.utils.file.FileUtils;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.mybatis.core.page.PageQuery;
|
||||
import cn.aixunkeji.common.mybatis.core.query.QueryBuilder;
|
||||
import cn.aixunkeji.common.oss.client.OssClient;
|
||||
import cn.aixunkeji.common.oss.enums.AccessPolicy;
|
||||
import cn.aixunkeji.common.oss.factory.OssFactory;
|
||||
import cn.aixunkeji.common.oss.model.Options;
|
||||
import cn.aixunkeji.common.oss.model.PutObjectResult;
|
||||
import cn.aixunkeji.resource.domain.SysOss;
|
||||
import cn.aixunkeji.resource.domain.SysOssExt;
|
||||
import cn.aixunkeji.resource.domain.bo.SysOssBo;
|
||||
import cn.aixunkeji.resource.domain.vo.SysOssVo;
|
||||
import cn.aixunkeji.resource.mapper.SysOssMapper;
|
||||
import cn.aixunkeji.resource.service.ISysOssService;
|
||||
import cn.aixunkeji.resource.storage.DataGovLocalFileStorage;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 文件上传 服务层实现
|
||||
*
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SysOssServiceImpl implements ISysOssService {
|
||||
|
||||
private static final String DATAGOV_LOCAL_SERVICE = "datagov-local";
|
||||
private static final String PRIVATE_SERVICE = "datagov-local-pvt";
|
||||
|
||||
private final SysOssMapper ossMapper;
|
||||
private final DataGovLocalFileStorage localFileStorage;
|
||||
|
||||
/**
|
||||
* 查询OSS对象存储列表
|
||||
*
|
||||
* @param bo OSS对象存储分页查询对象
|
||||
* @param pageQuery 分页查询实体类
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public PageResult<SysOssVo> queryPageList(SysOssBo bo, PageQuery pageQuery) {
|
||||
LambdaQueryWrapper<SysOss> lqw = buildQueryWrapper(bo);
|
||||
lqw.and(q -> q.isNull(SysOss::getService).or().ne(SysOss::getService, PRIVATE_SERVICE));
|
||||
lqw.and(q -> q.isNull(SysOss::getFileName).or().notLikeRight(SysOss::getFileName, "private-"));
|
||||
Page<SysOssVo> result = ossMapper.selectVoPage(pageQuery.build(), lqw);
|
||||
List<SysOssVo> filterResult = StreamUtils.toList(result.getRecords(), this::matchingUrl);
|
||||
result.setRecords(filterResult);
|
||||
return PageResult.build(result.getRecords(), result.getTotal());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应的 SysOssVo 列表
|
||||
*
|
||||
* @param ossIds 一组文件在数据库中的唯一标识集合
|
||||
* @return 包含 SysOssVo 对象的列表
|
||||
*/
|
||||
@Override
|
||||
public List<SysOssVo> listByIds(Collection<Long> ossIds) {
|
||||
SysOssServiceImpl ossService = SpringUtils.getAopProxy(this);
|
||||
List<Supplier<SysOssVo>> suppliers = ossIds.stream().map(id -> (Supplier<SysOssVo>) () -> {
|
||||
SysOssVo vo = ossService.getById(id);
|
||||
if (ObjectUtil.isNotNull(vo)) {
|
||||
try {
|
||||
return this.matchingUrl(vo);
|
||||
} catch (Exception ignored) {
|
||||
// 如果oss异常无法连接则将数据直接返回
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}).toList();
|
||||
List<SysOssVo> list = ThreadUtils.virtualSubmitAll(suppliers);
|
||||
list.removeAll(Collections.singleton(null));
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应文件的 URL 列表
|
||||
*
|
||||
* @param ossIds 以逗号分隔的 ossId 字符串
|
||||
* @return 以逗号分隔的文件 URL 字符串
|
||||
*/
|
||||
@Override
|
||||
public String selectUrlByIds(String ossIds) {
|
||||
List<Long> ids = StringUtils.splitTo(ossIds, Convert::toLong);
|
||||
SysOssServiceImpl ossService = SpringUtils.getAopProxy(this);
|
||||
List<Supplier<String>> suppliers = ids.stream().map(id -> (Supplier<String>) () -> {
|
||||
SysOssVo vo = ossService.getById(id);
|
||||
if (ObjectUtil.isNotNull(vo)) {
|
||||
try {
|
||||
return this.matchingUrl(vo).getUrl();
|
||||
} catch (Exception ignored) {
|
||||
// 如果oss异常无法连接则将数据直接返回
|
||||
return vo.getUrl();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}).toList();
|
||||
List<String> list = ThreadUtils.virtualSubmitAll(suppliers);
|
||||
list.removeAll(Collections.singleton(null));
|
||||
return StringUtils.joinComma(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 OSS 文件列表查询条件。
|
||||
*
|
||||
* @param bo 文件筛选条件
|
||||
* @return 包含文件名、后缀、归属服务和创建时间区间的查询包装器
|
||||
*/
|
||||
private LambdaQueryWrapper<SysOss> buildQueryWrapper(SysOssBo bo) {
|
||||
Map<String, Object> params = bo.getParams();
|
||||
return QueryBuilder.lambda(SysOss.class)
|
||||
.likeIfText(SysOss::getFileName, bo.getFileName())
|
||||
.likeIfText(SysOss::getOriginalName, bo.getOriginalName())
|
||||
.eqIfText(SysOss::getFileSuffix, bo.getFileSuffix())
|
||||
.eqIfText(SysOss::getUrl, bo.getUrl())
|
||||
.betweenParams(SysOss::getCreateTime, params, "beginCreateTime", "endCreateTime")
|
||||
.eqIfPresent(SysOss::getCreateBy, bo.getCreateBy())
|
||||
.eqIfText(SysOss::getService, bo.getService())
|
||||
.orderByAsc(SysOss::getOssId)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 ossId 从缓存或数据库中获取 SysOssVo 对象
|
||||
*
|
||||
* @param ossId 文件在数据库中的唯一标识
|
||||
* @return SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
@Override
|
||||
public SysOssVo getById(Long ossId) {
|
||||
// Check persisted classification on every path; cached metadata cannot bypass isolation.
|
||||
SysOssVo value = ossMapper.selectVoById(ossId);
|
||||
if (value != null) requireGeneral(value.getService(), value.getFileName(), value.getUrl());
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件下载方法,支持一次性下载完整文件
|
||||
*
|
||||
* @param ossId OSS对象ID
|
||||
*/
|
||||
@Override
|
||||
public ResponseEntity<byte[]> download(Long ossId) {
|
||||
SysOssVo sysOss = SpringUtils.getAopProxy(this).getById(ossId);
|
||||
if (ObjectUtil.isNull(sysOss)) {
|
||||
throw new ServiceException("文件数据不存在!");
|
||||
}
|
||||
String percentEncodedFileName = FileUtils.percentEncode(sysOss.getOriginalName());
|
||||
if (DATAGOV_LOCAL_SERVICE.equals(sysOss.getService()) && localFileStorage.enabled()) {
|
||||
try {
|
||||
SysOssExt ext = JsonUtils.parseObject(sysOss.getExt1(), SysOssExt.class);
|
||||
MediaType mediaType = ext == null || StringUtils.isBlank(ext.getContentType())
|
||||
? MediaType.APPLICATION_OCTET_STREAM
|
||||
: MediaType.parseMediaType(ext.getContentType());
|
||||
byte[] content = localFileStorage.read(sysOss.getFileName());
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Disposition,download-filename")
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=%s;filename*=utf-8''%s".formatted(percentEncodedFileName, percentEncodedFileName))
|
||||
.header("download-filename", percentEncodedFileName)
|
||||
.contentType(mediaType)
|
||||
.contentLength(content.length)
|
||||
.body(content);
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
throw new ServiceException("DataGov本地文件读取失败");
|
||||
}
|
||||
}
|
||||
return OssFactory.instance(sysOss.getService())
|
||||
.download(sysOss.getFileName(), (result, inputStream) -> {
|
||||
MediaType mediaType;
|
||||
try {
|
||||
mediaType = MediaType.parseMediaType(result.contentType());
|
||||
} catch (Exception e) {
|
||||
mediaType = MediaType.APPLICATION_OCTET_STREAM;
|
||||
}
|
||||
// 构建响应实体
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Disposition,download-filename")
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=%s;filename*=utf-8''%s".formatted(percentEncodedFileName, percentEncodedFileName))
|
||||
.header("download-filename", percentEncodedFileName)
|
||||
.contentType(mediaType)
|
||||
.contentLength(result.size())
|
||||
.body(IoUtil.readBytes(inputStream));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的 MultipartFile 对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
* @throws ServiceException 如果上传过程中发生异常,则抛出 ServiceException 异常
|
||||
*/
|
||||
@Override
|
||||
public SysOssVo upload(MultipartFile file, SysOssExt ossExt) {
|
||||
if (ObjectUtil.isNull(file) || file.isEmpty()) {
|
||||
throw new ServiceException("上传文件不能为空");
|
||||
}
|
||||
String originalfileName = file.getOriginalFilename();
|
||||
String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
|
||||
if (localFileStorage.enabled()) {
|
||||
try {
|
||||
DataGovLocalFileStorage.StoredFile stored = localFileStorage.store(file);
|
||||
SysOssExt ext = ossExt == null ? new SysOssExt() : ossExt;
|
||||
ext.setFileSize(stored.size());
|
||||
ext.setContentType(stored.contentType());
|
||||
return buildResultEntity(
|
||||
originalfileName,
|
||||
suffix,
|
||||
DATAGOV_LOCAL_SERVICE,
|
||||
PutObjectResult.form("local://" + stored.key(), stored.key(), "", stored.size()),
|
||||
ext
|
||||
);
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
}
|
||||
OssClient instance = OssFactory.instance();
|
||||
String pathKey = instance.buildPathKey(originalfileName);
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
PutObjectResult result = instance.upload(pathKey, inputStream, file.getSize(), Options.builder().setContentType(file.getContentType()));
|
||||
ossExt = ossExt == null ? new SysOssExt() : ossExt;
|
||||
ossExt.setFileSize(file.getSize());
|
||||
ossExt.setContentType(file.getContentType());
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, instance.clientId(), result, ossExt);
|
||||
} catch (IOException e) {
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的文件对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
@Override
|
||||
public SysOssVo upload(File file, SysOssExt ossExt) {
|
||||
if (ObjectUtil.isNull(file) || !file.isFile() || file.length() <= 0) {
|
||||
throw new ServiceException("上传文件不能为空");
|
||||
}
|
||||
String originalfileName = file.getName();
|
||||
String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
|
||||
if (localFileStorage.enabled()) {
|
||||
try {
|
||||
DataGovLocalFileStorage.StoredFile stored = localFileStorage.store(file);
|
||||
SysOssExt ext = ossExt == null ? new SysOssExt() : ossExt;
|
||||
ext.setFileSize(stored.size());
|
||||
ext.setContentType(stored.contentType());
|
||||
return buildResultEntity(
|
||||
originalfileName,
|
||||
suffix,
|
||||
DATAGOV_LOCAL_SERVICE,
|
||||
PutObjectResult.form("local://" + stored.key(), stored.key(), "", stored.size()),
|
||||
ext
|
||||
);
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
}
|
||||
OssClient instance = OssFactory.instance();
|
||||
String pathKey = instance.buildPathKey(originalfileName);
|
||||
PutObjectResult result = instance.upload(pathKey, file, Options.builder().setContentType(FileUtils.getMimeType(file.toPath())));
|
||||
SysOssExt ext1 = ossExt == null ? new SysOssExt() : ossExt;
|
||||
ext1.setFileSize(result.size());
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, instance.clientId(), result, ext1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装上传结果并持久化文件元数据。
|
||||
*
|
||||
* @param originalfileName 原始文件名
|
||||
* @param suffix 文件后缀
|
||||
* @param configKey 存储配置标识
|
||||
* @param result 上传结果
|
||||
* @param ext1 扩展属性对象
|
||||
* @return 持久化后的文件信息视图
|
||||
*/
|
||||
@NotNull
|
||||
private SysOssVo buildResultEntity(String originalfileName, String suffix, String configKey, PutObjectResult result, SysOssExt ext1) {
|
||||
requireGeneral(configKey, result.key(), result.url());
|
||||
SysOss oss = new SysOss();
|
||||
oss.setUrl(result.url());
|
||||
oss.setFileSuffix(suffix);
|
||||
oss.setFileName(result.key());
|
||||
oss.setOriginalName(originalfileName);
|
||||
oss.setService(configKey);
|
||||
oss.setExt1(JsonUtils.toJsonString(ext1));
|
||||
ossMapper.insert(oss);
|
||||
SysOssVo sysOssVo = MapstructUtils.convert(oss, SysOssVo.class);
|
||||
return this.matchingUrl(sysOssVo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增OSS对象存储
|
||||
*
|
||||
* @param bo SysOssBo 对象,包含待插入的数据
|
||||
* @return 插入操作是否成功的布尔值
|
||||
*/
|
||||
@Override
|
||||
public Boolean insertByBo(SysOssBo bo) {
|
||||
requireGeneral(bo.getService(), bo.getFileName(), bo.getUrl());
|
||||
SysOss oss = BeanUtil.toBean(bo, SysOss.class);
|
||||
boolean flag = ossMapper.insert(oss) > 0;
|
||||
if (flag) {
|
||||
bo.setOssId(oss.getOssId());
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除OSS对象存储
|
||||
*
|
||||
* @param ids OSS对象ID串
|
||||
* @param isValid 判断是否需要校验
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
|
||||
if (isValid) {
|
||||
// 做一些业务上的校验,判断是否需要校验
|
||||
}
|
||||
List<SysOss> list = ossMapper.selectByIds(ids);
|
||||
// Reject a mixed batch before deleting any public or private object.
|
||||
for (SysOss value : list) requireGeneral(value.getService(), value.getFileName(), value.getUrl());
|
||||
for (SysOss sysOss : list) {
|
||||
if (DATAGOV_LOCAL_SERVICE.equals(sysOss.getService()) && localFileStorage.enabled()) {
|
||||
try {
|
||||
localFileStorage.delete(sysOss.getFileName());
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
throw new ServiceException("DataGov本地文件删除失败");
|
||||
}
|
||||
} else {
|
||||
OssFactory.instance(sysOss.getService()).delete(sysOss.getFileName());
|
||||
}
|
||||
}
|
||||
return ossMapper.deleteByIds(ids) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 桶类型为 private 的URL 修改为临时URL时长为120s
|
||||
*
|
||||
* @param oss OSS对象
|
||||
* @return oss 匹配Url的OSS对象
|
||||
*/
|
||||
private SysOssVo matchingUrl(SysOssVo oss) {
|
||||
requireGeneral(oss.getService(), oss.getFileName(), oss.getUrl());
|
||||
if (DATAGOV_LOCAL_SERVICE.equals(oss.getService()) && localFileStorage.enabled()) {
|
||||
oss.setUrl("/resource/oss/download/" + oss.getOssId());
|
||||
return oss;
|
||||
}
|
||||
OssClient instance = OssFactory.instance(oss.getService());
|
||||
// 仅修改桶类型为 private 的URL,临时URL时长为120s
|
||||
if (instance.verifyConfig(config -> AccessPolicy.PRIVATE.equals(config.accessControlPolicyConfig().accessPolicy()))) {
|
||||
oss.setUrl(instance.presignGetUrl(oss.getFileName(), Duration.ofSeconds(120)));
|
||||
}
|
||||
return oss;
|
||||
}
|
||||
|
||||
private static void requireGeneral(String service, String key, String url) {
|
||||
String normalized = key == null ? "" : key.replace('\\', '/');
|
||||
if (PRIVATE_SERVICE.equals(service) || normalized.startsWith("private-")
|
||||
|| normalized.contains("/private-") || (url != null && url.contains("private-")))
|
||||
throw new ServiceException("PRIVATE_FILE_ACCESS_DENIED");
|
||||
}
|
||||
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package cn.aixunkeji.resource.service.impl;
|
||||
|
||||
import cn.aixunkeji.common.core.enums.PushSourceEnum;
|
||||
import cn.aixunkeji.common.core.enums.PushTypeEnum;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.common.push.dto.PushPayloadDTO;
|
||||
import cn.aixunkeji.resource.api.RemoteMessageService.*;
|
||||
import cn.aixunkeji.resource.service.ISysMessageService;
|
||||
import cn.aixunkeji.system.api.RemoteUserService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
|
||||
/** One fixed, scoped mailbox operation. It deliberately does not invoke the realtime push channel. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class WorkflowAlertMailboxService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate transactions;
|
||||
private final ISysMessageService messages;
|
||||
@DubboReference(check = false, timeout = 5000, retries = 0)
|
||||
private RemoteUserService users;
|
||||
|
||||
public MailboxReceipt read(WorkflowAlertMessage command) {
|
||||
validate(command);
|
||||
authorize(command);
|
||||
return lookup(command);
|
||||
}
|
||||
|
||||
public MailboxReceipt store(WorkflowAlertMessage command) {
|
||||
validate(command);
|
||||
authorize(command);
|
||||
try {
|
||||
var result = transactions.execute(tx -> {
|
||||
var original = lookup(command);
|
||||
if (!"NOT_FOUND".equals(original.state())) return original;
|
||||
long messageId = IdGeneratorUtil.nextLongId();
|
||||
jdbc.update("""
|
||||
INSERT INTO sys_workflow_alert_receipt
|
||||
(org_id,actor_id,idempotency_key,command_sha256,message_id,recipient_user_id,event_id,
|
||||
create_dept,create_by,update_by,create_time,update_time,del_flag,version)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,NOW(6),NOW(6),'0',0)
|
||||
""", command.orgId(), command.actorId(), command.idempotencyKey(), hash(command), messageId,
|
||||
command.recipientUserId(), command.eventId(), command.orgId(), command.actorId(), command.actorId());
|
||||
var payload = new PushPayloadDTO();
|
||||
payload.setMessageId(messageId);
|
||||
payload.setType(PushTypeEnum.MESSAGE.getType());
|
||||
payload.setSource(PushSourceEnum.BACKEND.getSource());
|
||||
payload.setMessage(command.summary());
|
||||
payload.setPath("/alert-events?eventId=" + command.eventId());
|
||||
payload.setData(java.util.Map.of("title", "告警通知", "eventId", Long.toString(command.eventId())));
|
||||
var saved = messages.storeUsers(List.of(command.recipientUserId()), payload);
|
||||
if (saved == null || !Long.valueOf(messageId).equals(saved.getMessageId())) {
|
||||
throw new IllegalStateException("WORKFLOW_MAILBOX_WRITE_UNCONFIRMED");
|
||||
}
|
||||
authorize(command);
|
||||
var confirmed = lookup(command);
|
||||
if (!"STORED".equals(confirmed.state())) throw new IllegalStateException("WORKFLOW_MAILBOX_WRITE_UNCONFIRMED");
|
||||
return confirmed;
|
||||
});
|
||||
return result == null ? unknown() : result;
|
||||
} catch (DuplicateKeyException race) {
|
||||
// A concurrent call can only read the same committed command, never create a second message.
|
||||
return lookup(command);
|
||||
}
|
||||
}
|
||||
|
||||
private MailboxReceipt lookup(WorkflowAlertMessage command) {
|
||||
var rows = jdbc.query("""
|
||||
SELECT r.command_sha256,r.message_id,r.recipient_user_id,r.event_id,r.create_time,
|
||||
m.message_id AS stored_message_id,m.send_user_ids,m.message
|
||||
FROM sys_workflow_alert_receipt r LEFT JOIN sys_message m ON m.message_id=r.message_id
|
||||
WHERE r.org_id=? AND r.actor_id=? AND r.idempotency_key=? AND r.del_flag='0'
|
||||
""", (rs, row) -> new Stored(rs.getString("command_sha256"), rs.getLong("message_id"),
|
||||
rs.getLong("recipient_user_id"), rs.getLong("event_id"), rs.getObject("create_time", LocalDateTime.class),
|
||||
rs.getObject("stored_message_id", Long.class), rs.getString("send_user_ids"), rs.getString("message")),
|
||||
command.orgId(), command.actorId(), command.idempotencyKey());
|
||||
if (rows.isEmpty()) return new MailboxReceipt("NOT_FOUND", null, "WORKFLOW_MAILBOX_NOT_FOUND", null);
|
||||
var row = rows.getFirst();
|
||||
if (rows.size() != 1 || !hash(command).equals(row.sha()) || row.recipient() != command.recipientUserId()
|
||||
|| row.event() != command.eventId()) return new MailboxReceipt("CONFLICT", null, "WORKFLOW_MAILBOX_KEY_CONFLICT", null);
|
||||
if (!Long.valueOf(row.message()).equals(row.storedMessage())
|
||||
|| !Long.toString(command.recipientUserId()).equals(row.recipients()) || !command.summary().equals(row.summary())) {
|
||||
return unknown();
|
||||
}
|
||||
return new MailboxReceipt("STORED", row.message(), null, row.at());
|
||||
}
|
||||
|
||||
private void authorize(WorkflowAlertMessage command) {
|
||||
var grant = users.resolveWorkflowActor(command.actorId(), command.orgId(), "ALERT_NOTIFY");
|
||||
var now = Instant.now();
|
||||
if (grant == null || !grant.allowed() || grant.userId() != command.actorId() || grant.deptId() != command.orgId()
|
||||
|| !"ALERT_NOTIFY".equals(grant.purpose()) || grant.checkedAt() == null
|
||||
|| grant.checkedAt().isBefore(now.minusSeconds(30)) || grant.checkedAt().isAfter(now.plusSeconds(5))) {
|
||||
throw new IllegalStateException("WORKFLOW_MAILBOX_ACTOR_DENIED");
|
||||
}
|
||||
var recipients = users.selectListByIds(List.of(command.recipientUserId()));
|
||||
if (recipients == null || recipients.size() != 1) throw new IllegalStateException("WORKFLOW_MAILBOX_RECIPIENT_DENIED");
|
||||
var recipient = recipients.getFirst();
|
||||
if (recipient == null || !Long.valueOf(command.recipientUserId()).equals(recipient.getUserId())
|
||||
|| !Long.valueOf(command.orgId()).equals(recipient.getDeptId()) || !"0".equals(recipient.getStatus())) {
|
||||
throw new IllegalStateException("WORKFLOW_MAILBOX_RECIPIENT_DENIED");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validate(WorkflowAlertMessage command) {
|
||||
if (command == null || command.actorId() <= 0 || command.orgId() <= 0 || command.eventId() <= 0 || command.recipientUserId() <= 0
|
||||
|| command.idempotencyKey() == null || !command.idempotencyKey().matches("[A-Za-z0-9:_-]{16,128}")
|
||||
|| command.eventVersion() == null || !command.eventVersion().matches("[0-9]{1,19}")
|
||||
|| command.ownerSha256() == null || !command.ownerSha256().matches("[a-f0-9]{64}")
|
||||
|| command.alertRequestId() == null || !command.alertRequestId().matches("[1-9][0-9]{0,18}")
|
||||
|| command.summary() == null || command.summary().isBlank() || command.summary().length() > 500
|
||||
|| command.summary().chars().anyMatch(Character::isISOControl)) {
|
||||
throw new IllegalArgumentException("WORKFLOW_MAILBOX_COMMAND_INVALID");
|
||||
}
|
||||
}
|
||||
private static String hash(Object value) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JsonUtils.toJsonString(value).getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
private static MailboxReceipt unknown() { return new MailboxReceipt("UNKNOWN", null, "WORKFLOW_MAILBOX_UNCONFIRMED", null); }
|
||||
private record Stored(String sha, long message, long recipient, long event, LocalDateTime at,
|
||||
Long storedMessage, String recipients, String summary) { }
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* Minimal DataGov-owned local file store for the retained RCP6 file capability.
|
||||
* It is not a Hive object-store decision and is not shared with another project.
|
||||
*/
|
||||
@Component
|
||||
public class DataGovLocalFileStorage {
|
||||
|
||||
private static final Set<String> ALLOWED_SUFFIXES = Set.of(
|
||||
".txt", ".csv", ".json", ".pdf", ".png", ".jpg", ".jpeg"
|
||||
);
|
||||
|
||||
private final boolean enabled;
|
||||
private final Path root;
|
||||
private final long maxBytes;
|
||||
|
||||
public DataGovLocalFileStorage(
|
||||
@Value("${aixun.datagov.local-file.enabled:false}") boolean enabled,
|
||||
@Value("${aixun.datagov.local-file.root:/var/lib/aixun-datagov/files}") String root,
|
||||
@Value("${aixun.datagov.local-file.max-bytes:10485760}") long maxBytes
|
||||
) {
|
||||
this.enabled = enabled;
|
||||
this.root = Path.of(root).toAbsolutePath().normalize();
|
||||
this.maxBytes = maxBytes;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void initialize() throws IOException {
|
||||
if (enabled) {
|
||||
Files.createDirectories(root);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public StoredFile store(MultipartFile file) throws IOException {
|
||||
validate(file.getOriginalFilename(), file.getSize());
|
||||
byte[] content = file.getBytes();
|
||||
return store(file.getOriginalFilename(), content);
|
||||
}
|
||||
|
||||
public StoredFile store(File file) throws IOException {
|
||||
validate(file.getName(), file.length());
|
||||
return store(file.getName(), Files.readAllBytes(file.toPath()));
|
||||
}
|
||||
|
||||
public byte[] read(String key) throws IOException {
|
||||
rejectPrivateKey(key);
|
||||
return Files.readAllBytes(resolve(key));
|
||||
}
|
||||
|
||||
public void delete(String key) throws IOException {
|
||||
rejectPrivateKey(key);
|
||||
Files.deleteIfExists(resolve(key));
|
||||
}
|
||||
|
||||
public long privateLimit() { return maxBytes; }
|
||||
|
||||
/** Reservation is persisted by Resource before this key is used for any physical write. */
|
||||
public String newPrivateKey(String originalName, long length) {
|
||||
validatePrivate(originalName, length);
|
||||
return "private-" + UUID.randomUUID() + suffix(originalName);
|
||||
}
|
||||
|
||||
public void validatePrivate(String originalName, long length) {
|
||||
if (!enabled || length <= 0 || length > maxBytes) throw new IllegalArgumentException("PRIVATE_FILE_SIZE");
|
||||
String ext = suffix(originalName);
|
||||
if (!ALLOWED_SUFFIXES.contains(ext) && !Set.of(".jsonl",".md",".docx",".doc",".zip").contains(ext))
|
||||
throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
}
|
||||
|
||||
/** Caller holds the persistent operation row lock; partial prior writes are recovered byte-for-byte. */
|
||||
public void appendPrivate(String key, long offset, byte[] bytes, long expectedLength) throws IOException {
|
||||
Path path = privatePath(key);
|
||||
if (offset < 0 || bytes.length < 1 || bytes.length > 65_536
|
||||
|| offset > expectedLength - bytes.length || expectedLength > maxBytes)
|
||||
throw new IllegalArgumentException("PRIVATE_FILE_RANGE");
|
||||
try (FileChannel file = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.READ,
|
||||
StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
||||
long size = file.size();
|
||||
if (size < offset || size > expectedLength) throw new IOException("PRIVATE_FILE_OFFSET");
|
||||
int existing = (int) Math.min(bytes.length, size - offset);
|
||||
ByteBuffer prior = ByteBuffer.allocate(existing);
|
||||
file.position(offset);
|
||||
while (prior.hasRemaining()) if (file.read(prior) < 0) throw new IOException("PRIVATE_FILE_TRUNCATED");
|
||||
for (int i = 0; i < existing; i++)
|
||||
if (prior.array()[i] != bytes[i]) throw new IOException("PRIVATE_FILE_CONFLICT");
|
||||
if (existing < bytes.length) {
|
||||
if (size != offset + existing) throw new IOException("PRIVATE_FILE_OFFSET");
|
||||
file.position(size);
|
||||
ByteBuffer remainder = ByteBuffer.wrap(bytes, existing, bytes.length - existing);
|
||||
while (remainder.hasRemaining()) file.write(remainder);
|
||||
file.force(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Entire bounded immutable artifact is checked before returning any requested bytes. */
|
||||
public byte[] readPrivate(String key, long expectedLength, String expectedSha) throws IOException {
|
||||
if (!enabled || expectedLength <= 0 || expectedLength > maxBytes || expectedLength > Integer.MAX_VALUE)
|
||||
throw new IOException("PRIVATE_FILE_SIZE");
|
||||
try (FileChannel file = FileChannel.open(privatePath(key), StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (file.size() != expectedLength) throw new IOException("PRIVATE_FILE_LENGTH");
|
||||
ByteBuffer bytes = ByteBuffer.allocate((int) expectedLength);
|
||||
while (bytes.hasRemaining()) if (file.read(bytes) < 0) throw new IOException("PRIVATE_FILE_TRUNCATED");
|
||||
if (file.size() != expectedLength || !privateSha(bytes.array()).equals(expectedSha))
|
||||
throw new IOException("PRIVATE_FILE_INTEGRITY");
|
||||
return bytes.array();
|
||||
}
|
||||
}
|
||||
|
||||
public void validatePrivateContent(String originalName, byte[] bytes, String mime) {
|
||||
validatePrivate(originalName, bytes.length);
|
||||
String ext = suffix(originalName);
|
||||
String detected;
|
||||
if (".jsonl".equals(ext)) {
|
||||
requireUtf8Text(bytes);
|
||||
String value = new String(bytes, StandardCharsets.UTF_8);
|
||||
int count = 0;
|
||||
for (String line : value.split("\\r?\\n", -1)) {
|
||||
if (line.isBlank()) continue;
|
||||
if (line.getBytes(StandardCharsets.UTF_8).length > 65_536 || !line.stripLeading().startsWith("{"))
|
||||
throw new IllegalArgumentException("PRIVATE_JSONL_ROW");
|
||||
// Reuse the application's bounded JSON parser, never execute imported text.
|
||||
Object row = cn.aixunkeji.common.json.utils.JsonUtils.parseObject(line, java.util.Map.class);
|
||||
if (row == null || ++count > 100_000) throw new IllegalArgumentException("PRIVATE_JSONL_ROW");
|
||||
}
|
||||
if (count == 0) throw new IllegalArgumentException("PRIVATE_JSONL_EMPTY");
|
||||
detected = "application/x-ndjson";
|
||||
} else if(".md".equals(ext)) { requireUtf8Text(bytes);detected="text/markdown";
|
||||
} else if(".doc".equals(ext)) {
|
||||
detected=requireHeader(bytes,new byte[]{(byte)0xd0,(byte)0xcf,0x11,(byte)0xe0,(byte)0xa1,(byte)0xb1,0x1a,(byte)0xe1},"application/msword");
|
||||
} else if(".docx".equals(ext)||".zip".equals(ext)) {
|
||||
KnowledgeArchiveSafety.check(bytes,".docx".equals(ext));
|
||||
detected=".docx".equals(ext)?"application/vnd.openxmlformats-officedocument.wordprocessingml.document":"application/zip";
|
||||
} else {
|
||||
detected = detectContentType(ext, bytes);
|
||||
}
|
||||
if (!detected.equals(mime)) throw new IllegalArgumentException("PRIVATE_FILE_MIME");
|
||||
}
|
||||
|
||||
private Path privatePath(String key) throws IOException {
|
||||
if (!enabled || key == null || !key.matches("private-[a-f0-9-]{36}\\.(txt|csv|json|jsonl|pdf|png|jpg|jpeg|md|docx|doc|zip)"))
|
||||
throw new IOException("PRIVATE_FILE_KEY");
|
||||
Path path = resolve(key);
|
||||
for (Path part = root; part != null; part = part.getParent())
|
||||
if (Files.isSymbolicLink(part)) throw new IOException("PRIVATE_FILE_SYMLINK");
|
||||
if (Files.isSymbolicLink(path)) throw new IOException("PRIVATE_FILE_SYMLINK");
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void rejectPrivateKey(String key) {
|
||||
if (key != null && Path.of(key).normalize().getFileName() != null
|
||||
&& Path.of(key).normalize().getFileName().toString().startsWith("private-"))
|
||||
throw new IllegalArgumentException("PRIVATE_FILE_ACCESS_DENIED");
|
||||
}
|
||||
/** Invoked only after the private knowledge Owner has persisted erasure intent and authorized this exact binding. */
|
||||
public void erasePrivateKnowledge(String key) throws IOException { Files.deleteIfExists(privatePath(key)); }
|
||||
|
||||
private static String privateSha(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
|
||||
private void validate(String originalName, long size) {
|
||||
if (!enabled) {
|
||||
throw new IllegalStateException("DataGov local file storage is disabled");
|
||||
}
|
||||
if (size <= 0 || size > maxBytes) {
|
||||
throw new IllegalArgumentException("文件大小必须在1字节到10MB之间");
|
||||
}
|
||||
String suffix = suffix(originalName);
|
||||
if (!ALLOWED_SUFFIXES.contains(suffix)) {
|
||||
throw new IllegalArgumentException("文件类型不在M0允许列表中");
|
||||
}
|
||||
}
|
||||
|
||||
private StoredFile store(String originalName, byte[] content) throws IOException {
|
||||
validate(originalName, content.length);
|
||||
String suffix = suffix(originalName);
|
||||
String contentType = detectContentType(suffix, content);
|
||||
String key = newKey(originalName);
|
||||
Files.write(resolve(key), content, StandardOpenOption.CREATE_NEW);
|
||||
return new StoredFile(key, content.length, contentType);
|
||||
}
|
||||
|
||||
private String detectContentType(String suffix, byte[] content) {
|
||||
return switch (suffix) {
|
||||
case ".pdf" -> requireHeader(content, new byte[]{'%', 'P', 'D', 'F', '-'}, "application/pdf");
|
||||
case ".png" -> requireHeader(content,
|
||||
new byte[]{(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A}, "image/png");
|
||||
case ".jpg", ".jpeg" -> requireHeader(content,
|
||||
new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}, "image/jpeg");
|
||||
case ".json" -> {
|
||||
requireUtf8Text(content);
|
||||
String value = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(content)).toString().stripLeading();
|
||||
if (!(value.startsWith("{") || value.startsWith("["))) {
|
||||
throw new IllegalArgumentException("JSON文件头不合法");
|
||||
}
|
||||
yield "application/json";
|
||||
}
|
||||
case ".csv" -> {
|
||||
requireUtf8Text(content);
|
||||
yield "text/csv";
|
||||
}
|
||||
case ".txt" -> {
|
||||
requireUtf8Text(content);
|
||||
yield "text/plain";
|
||||
}
|
||||
default -> throw new IllegalArgumentException("文件类型不在M0允许列表中");
|
||||
};
|
||||
}
|
||||
|
||||
private String requireHeader(byte[] content, byte[] expected, String contentType) {
|
||||
if (content.length < expected.length || !Arrays.equals(Arrays.copyOf(content, expected.length), expected)) {
|
||||
throw new IllegalArgumentException("文件内容与扩展名不匹配");
|
||||
}
|
||||
return contentType;
|
||||
}
|
||||
|
||||
private void requireUtf8Text(byte[] content) {
|
||||
try {
|
||||
StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(content));
|
||||
} catch (CharacterCodingException e) {
|
||||
throw new IllegalArgumentException("文本文件必须使用UTF-8编码");
|
||||
}
|
||||
for (byte value : content) {
|
||||
if (value == 0) {
|
||||
throw new IllegalArgumentException("文本文件包含非法二进制内容");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String newKey(String originalName) {
|
||||
return UUID.randomUUID() + suffix(originalName);
|
||||
}
|
||||
|
||||
private String suffix(String originalName) {
|
||||
String safeName = Path.of(originalName == null ? "" : originalName).getFileName().toString();
|
||||
int index = safeName.lastIndexOf('.');
|
||||
return index < 0 ? "" : safeName.substring(index).toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private Path resolve(String key) {
|
||||
Path resolved = root.resolve(key).normalize();
|
||||
if (!resolved.startsWith(root) || resolved.equals(root)) {
|
||||
throw new IllegalArgumentException("非法文件路径");
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
public record StoredFile(String key, long size, String contentType) {
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/** Private knowledge archives are inspected in memory and never extracted into a filesystem. */
|
||||
final class KnowledgeArchiveSafety {
|
||||
private KnowledgeArchiveSafety() { }
|
||||
static void check(byte[] bytes,boolean docx) {
|
||||
if(bytes.length>5_242_880||bytes.length<4||bytes[0]!='P'||bytes[1]!='K') throw invalid();
|
||||
long total=0;int count=0;var names=new HashSet<String>();boolean document=false,skill=false;
|
||||
try(var zip=new ZipInputStream(new ByteArrayInputStream(bytes))) {
|
||||
java.util.zip.ZipEntry entry;byte[] buffer=new byte[8192];
|
||||
while((entry=zip.getNextEntry())!=null) {
|
||||
String name=entry.getName(),lower=name.toLowerCase(Locale.ROOT);
|
||||
if(++count>300||name.length()>240||name.startsWith("/")||name.contains("\\")||name.contains(":")||name.contains("\0")||java.util.Arrays.asList(name.split("/")).contains("..")||!names.add(name)) throw invalid();
|
||||
if(lower.endsWith("vbaproject.bin")||lower.endsWith(".exe")||lower.endsWith(".sh")||lower.endsWith(".js")||lower.endsWith(".jar")||lower.endsWith(".class")) throw invalid();
|
||||
if(!docx&&!entry.isDirectory()&&!lower.endsWith(".md")&&!lower.endsWith(".txt")&&!lower.endsWith(".json")&&!lower.endsWith(".yaml")&&!lower.endsWith(".yml")) throw invalid();
|
||||
long size=0;int read;while((read=zip.read(buffer))!=-1) { size+=read;total+=read;if(size>4_194_304||total>16_777_216||total>Math.max(1_048_576L,bytes.length*100L)) throw invalid(); }
|
||||
document|=name.equals("word/document.xml");skill|=name.equals("SKILL.md");
|
||||
}
|
||||
} catch(java.io.IOException e) { throw invalid(); }
|
||||
if(count==0||(docx?!document:!skill)) throw invalid();
|
||||
}
|
||||
private static IllegalArgumentException invalid() { return new IllegalArgumentException("PRIVATE_FILE_ARCHIVE_INVALID"); }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# Tomcat
|
||||
server:
|
||||
port: 9204
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
application:
|
||||
# 应用名称
|
||||
name: aixun-resource
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: @profiles.active@
|
||||
|
||||
--- # nacos 配置
|
||||
spring:
|
||||
cloud:
|
||||
nacos:
|
||||
# nacos 服务地址
|
||||
server-addr: @nacos.server@
|
||||
username: @nacos.username@
|
||||
password: @nacos.password@
|
||||
discovery:
|
||||
# 注册组
|
||||
group: DEFAULT_GROUP
|
||||
namespace: public
|
||||
config:
|
||||
# 配置组
|
||||
group: DEFAULT_GROUP
|
||||
namespace: public
|
||||
config:
|
||||
import:
|
||||
- optional:nacos:application-common.yml
|
||||
- optional:nacos:datasource.yml
|
||||
- optional:nacos:${spring.application.name}.yml
|
||||
@@ -0,0 +1,10 @@
|
||||
Spring Boot Version: ${spring-boot.version}
|
||||
Spring Application Name: ${spring.application.name}
|
||||
_
|
||||
(_)
|
||||
_ __ _ _ ___ _ _ _ ______ _ __ ___ ___ ___ _ _ _ __ ___ ___
|
||||
| '__| | | |/ _ \| | | | |______| '__/ _ \/ __|/ _ \| | | | '__/ __/ _ \
|
||||
| | | |_| | (_) | |_| | | | | | __/\__ \ (_) | |_| | | | (_| __/
|
||||
|_| \__,_|\___/ \__, |_| |_| \___||___/\___/ \__,_|_| \___\___|
|
||||
__/ |
|
||||
|___/
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||
<!-- 日志存放路径 -->
|
||||
<property name="log.path" value="logs/${project.artifactId}"/>
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="console.log.pattern"
|
||||
value="%cyan(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
|
||||
|
||||
<!-- 控制台输出 -->
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${console.log.pattern}</pattern>
|
||||
<charset>utf-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<include resource="logback-common.xml" />
|
||||
|
||||
<include resource="logback-logstash.xml" />
|
||||
|
||||
<!-- 开启 skywalking 日志收集 -->
|
||||
<include resource="logback-skylog.xml" />
|
||||
|
||||
<!--系统操作日志-->
|
||||
<root level="info">
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,3 @@
|
||||
java包使用 `.` 分割 resource 目录使用 `/` 分割
|
||||
<br>
|
||||
此文件目的 防止文件夹粘连找不到 `xml` 文件
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="cn.aixunkeji.resource.mapper.SysMessageMapper">
|
||||
|
||||
</mapper>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="cn.aixunkeji.resource.mapper.SysOssConfigMapper">
|
||||
|
||||
</mapper>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="cn.aixunkeji.resource.mapper.SysOssMapper">
|
||||
|
||||
</mapper>
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.aixunkeji.datagov.resource.privatefile;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.aixunkeji.resource.storage.DataGovLocalFileStorage;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.IOException;
|
||||
import java.util.function.Supplier;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class KnowledgePrivateFileEraseTest {
|
||||
final PrivateBusinessFileJdbcRepository repository=mock(PrivateBusinessFileJdbcRepository.class);
|
||||
final DataGovLocalFileStorage storage=mock(DataGovLocalFileStorage.class);
|
||||
final PrivateBusinessFileAuthorizationGateway authorization=mock(PrivateBusinessFileAuthorizationGateway.class);
|
||||
final PrivateBusinessFileService service=new PrivateBusinessFileService(repository,storage,authorization);
|
||||
final WriteQuery query=new WriteQuery(new Context(1,10,20,20,"governance","delegation","request"),"a".repeat(64));
|
||||
@BeforeEach void transaction() { when(repository.transaction(any())).thenAnswer(i->((Supplier<?>)i.getArgument(0)).get()); }
|
||||
@Test void knowledgeEraseRechecksOwnerThenDeletesExactFile() throws Exception { var stored=stored("WORKBENCH_KNOWLEDGE_ATTACHMENT","KNOWLEDGE_ORIGINAL",WriteState.BOUND);when(repository.find(query)).thenReturn(stored);assertEquals(WriteState.CANCELED,service.eraseKnowledgeOriginal(query).state());var order=inOrder(authorization,storage,repository);order.verify(authorization).require(argThat(q->q.action()==Action.ERASE_KNOWLEDGE&&q.binding().equals(stored.binding())));order.verify(storage).erasePrivateKnowledge("private/exact.md");order.verify(repository).eraseKnowledge(stored); }
|
||||
@Test void financialTargetCannotUseKnowledgeErase() { when(repository.find(query)).thenReturn(stored("FINANCIAL_INPUT","KNOWLEDGE_ORIGINAL",WriteState.BOUND));assertThrows(IllegalStateException.class,()->service.eraseKnowledgeOriginal(query));verifyNoInteractions(authorization,storage); }
|
||||
@Test void revokedOwnerCannotErase() { when(repository.find(query)).thenReturn(stored("WORKBENCH_KNOWLEDGE_ATTACHMENT","KNOWLEDGE_ORIGINAL",WriteState.BOUND));when(authorization.require(any())).thenThrow(new IllegalStateException("DENIED"));assertThrows(IllegalStateException.class,()->service.eraseKnowledgeOriginal(query));verifyNoInteractions(storage);verify(repository,never()).eraseKnowledge(any()); }
|
||||
@Test void physicalFailureNeverMarksDeleted() throws Exception { when(repository.find(query)).thenReturn(stored("WORKBENCH_KNOWLEDGE_ATTACHMENT","KNOWLEDGE_ORIGINAL",WriteState.BOUND));doThrow(new IOException()).when(storage).erasePrivateKnowledge(any());assertEquals("PRIVATE_FILE_ERASE_UNKNOWN",assertThrows(IllegalStateException.class,()->service.eraseKnowledgeOriginal(query)).getMessage());verify(repository,never()).eraseKnowledge(any()); }
|
||||
@Test void cancelledBindingCanReconcileSameErase() { when(repository.find(query)).thenReturn(stored("WORKBENCH_KNOWLEDGE_ATTACHMENT","KNOWLEDGE_ORIGINAL",WriteState.CANCELED));assertEquals(WriteState.CANCELED,service.eraseKnowledgeOriginal(query).state()); }
|
||||
private PrivateBusinessFileJdbcRepository.Stored stored(String type,String purpose,WriteState state) { var target=new Target("governance",type,"object",1,FileUse.EVIDENCE,purpose,"USER:10","source.md","b".repeat(64),5,"text/markdown",null,null);return new PrivateBusinessFileJdbcRepository.Stored(20,20,query.operationKey(),"c".repeat(64),target.bytesSha256(),"100","private/exact.md",target,state,5,10); }
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package cn.aixunkeji.datagov.resource.privatefile;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.aixunkeji.resource.storage.DataGovLocalFileStorage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class OriginalIngestionPrivateFileTest {
|
||||
@Test void wordIngestionReachesAuthorizationButOtherBusinessCannotUseWordException(){
|
||||
var db=mock(PrivateBusinessFileJdbcRepository.class);var storage=mock(DataGovLocalFileStorage.class);
|
||||
var auth=mock(PrivateBusinessFileAuthorizationGateway.class);var service=new PrivateBusinessFileService(db,storage,auth);
|
||||
when(auth.require(any())).thenThrow(new IllegalStateException("OWNER_DENIED"));
|
||||
for(String name:java.util.List.of("file.doc","file.docx")){
|
||||
assertEquals("OWNER_DENIED",assertThrows(IllegalStateException.class,()->service.stage(request(name,"INGESTION_ORIGINAL_FILE"))).getMessage());
|
||||
assertEquals("PRIVATE_FILE_TYPE",assertThrows(IllegalArgumentException.class,()->service.stage(request(name,"OTHER"))).getMessage());
|
||||
}
|
||||
verify(auth,times(2)).require(any());verifyNoInteractions(db);
|
||||
}
|
||||
private StageRequest request(String name,String type){
|
||||
var target=new Target("dataops",type,"id",1,FileUse.EVIDENCE,type,"USER:7",name,"a".repeat(64),20,"application/octet-stream",null,null);
|
||||
return new StageRequest(new Context(1,7,8,8,"aixun-dataops","delegation","request"),target,"b".repeat(64),target.bytesSha256());
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package cn.aixunkeji.resource.service.impl;
|
||||
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.resource.api.RemoteMessageService.*;
|
||||
import cn.aixunkeji.resource.service.ISysMessageService;
|
||||
import cn.aixunkeji.system.api.RemoteUserService;
|
||||
import cn.aixunkeji.system.api.domain.vo.RemoteUserVo;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.SimpleTransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.sql.ResultSet;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class WorkflowAlertMailboxServiceTest {
|
||||
private final WorkflowAlertMessage command = new WorkflowAlertMessage(7, 9, 1, 8,
|
||||
"schedule-alert-notification-test", "4", "a".repeat(64), "99", "告警事件通知:失败任务");
|
||||
private final JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
private final PlatformTransactionManager tx = mock(PlatformTransactionManager.class);
|
||||
private final ISysMessageService messages = mock(ISysMessageService.class);
|
||||
private final RemoteUserService users = mock(RemoteUserService.class);
|
||||
private final WorkflowAlertMailboxService service = new WorkflowAlertMailboxService(jdbc, new TransactionTemplate(tx), messages);
|
||||
private final AtomicBoolean stored = new AtomicBoolean();
|
||||
private final AtomicLong messageId = new AtomicLong(100);
|
||||
private String storedSha;
|
||||
|
||||
@BeforeAll static void beans() {
|
||||
var beans = new org.springframework.beans.factory.support.DefaultListableBeanFactory();
|
||||
beans.registerSingleton("jsonMapper", JsonMapper.builder().findAndAddModules().build());
|
||||
beans.registerSingleton("identifierGenerator", (com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator) entity -> 100L);
|
||||
new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(beans);
|
||||
}
|
||||
@BeforeEach void setup() throws Exception {
|
||||
ReflectionTestUtils.setField(service, "users", users);
|
||||
when(tx.getTransaction(any())).thenAnswer(i -> new SimpleTransactionStatus());
|
||||
when(users.resolveWorkflowActor(7, 9, "ALERT_NOTIFY")).thenAnswer(i ->
|
||||
new RemoteUserService.AssetActorDecision(7, 9, "ALERT_NOTIFY", true, null, Instant.now()));
|
||||
when(users.selectListByIds(List.of(8L))).thenReturn(List.of(recipient(9)));
|
||||
storedSha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
|
||||
.digest(JsonUtils.toJsonString(command).getBytes(StandardCharsets.UTF_8)));
|
||||
when(messages.storeUsers(eq(List.of(8L)), any())).thenAnswer(i -> {
|
||||
cn.aixunkeji.common.push.dto.PushPayloadDTO payload = i.getArgument(1);
|
||||
assertThat(payload.getPath()).isEqualTo("/alert-events?eventId=1");
|
||||
messageId.set(payload.getMessageId()); stored.set(true); return payload;
|
||||
});
|
||||
when(jdbc.query(anyString(), org.mockito.ArgumentMatchers.<RowMapper<Object>>any(), eq(9L), eq(7L), eq(command.idempotencyKey())))
|
||||
.thenAnswer(i -> {
|
||||
if (!stored.get()) return List.of();
|
||||
ResultSet row = mock(ResultSet.class);
|
||||
when(row.getString("command_sha256")).thenReturn(storedSha);
|
||||
when(row.getLong("message_id")).thenReturn(messageId.get());
|
||||
when(row.getLong("recipient_user_id")).thenReturn(8L);
|
||||
when(row.getLong("event_id")).thenReturn(1L);
|
||||
when(row.getObject("create_time", LocalDateTime.class)).thenReturn(LocalDateTime.now());
|
||||
when(row.getObject("stored_message_id", Long.class)).thenReturn(messageId.get());
|
||||
when(row.getString("send_user_ids")).thenReturn("8");
|
||||
when(row.getString("message")).thenReturn(command.summary());
|
||||
RowMapper<?> mapper = i.getArgument(1);
|
||||
return List.of(mapper.mapRow(row, 0));
|
||||
});
|
||||
}
|
||||
private RemoteUserVo recipient(long org) { var user = new RemoteUserVo(); user.setUserId(8L); user.setDeptId(org); user.setStatus("0"); return user; }
|
||||
|
||||
@Test void storesOneOriginalMessageAndReplaysWithoutSecondInsertion() {
|
||||
assertThat(service.store(command).state()).isEqualTo("STORED");
|
||||
assertThat(service.store(command).messageId()).isEqualTo(messageId.get());
|
||||
verify(messages, times(1)).storeUsers(eq(List.of(8L)), any());
|
||||
verify(tx, times(2)).commit(any());
|
||||
}
|
||||
@Test void observationIsReadOnlyAndMissingMessageIsNotSuccess() {
|
||||
assertThat(service.read(command).state()).isEqualTo("NOT_FOUND");
|
||||
verifyNoInteractions(messages, tx);
|
||||
verify(jdbc, never()).update(anyString(), org.mockito.ArgumentMatchers.<Object[]>any());
|
||||
}
|
||||
@Test void sameKeyChangedCommandCannotCreateAnotherMessage() {
|
||||
stored.set(true); storedSha = "b".repeat(64);
|
||||
assertThat(service.store(command).state()).isEqualTo("CONFLICT");
|
||||
verifyNoInteractions(messages);
|
||||
}
|
||||
@Test void movedOrInactiveRecipientCannotReadOrCreateMailboxMessage() {
|
||||
when(users.selectListByIds(List.of(8L))).thenReturn(List.of(recipient(10)));
|
||||
assertThatThrownBy(() -> service.store(command)).hasMessage("WORKFLOW_MAILBOX_RECIPIENT_DENIED");
|
||||
assertThatThrownBy(() -> service.read(command)).hasMessage("WORKFLOW_MAILBOX_RECIPIENT_DENIED");
|
||||
verifyNoInteractions(messages, jdbc, tx);
|
||||
}
|
||||
@Test void messageWriteFailureRollsBackReceiptTransaction() {
|
||||
when(messages.storeUsers(anyList(), any())).thenThrow(new IllegalStateException("write failed"));
|
||||
assertThatThrownBy(() -> service.store(command)).hasMessage("write failed");
|
||||
verify(tx).rollback(any());
|
||||
verify(tx, never()).commit(any());
|
||||
}
|
||||
@Test void recipientChangeDuringWriteRollsBack() {
|
||||
when(users.selectListByIds(List.of(8L))).thenReturn(List.of(recipient(9)), List.of(recipient(10)));
|
||||
assertThatThrownBy(() -> service.store(command)).hasMessage("WORKFLOW_MAILBOX_RECIPIENT_DENIED");
|
||||
verify(tx).rollback(any());
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class DataGovLocalFileStorageTest {
|
||||
@Test
|
||||
void privateOriginalsRoundTripWithoutChangingBytes() throws Exception {
|
||||
DataGovLocalFileStorage storage = new DataGovLocalFileStorage(true, root.toRealPath().toString(), 10485760);
|
||||
storage.initialize();
|
||||
var docx = new java.io.ByteArrayOutputStream();
|
||||
try (var zip = new java.util.zip.ZipOutputStream(docx)) {
|
||||
zip.putNextEntry(new java.util.zip.ZipEntry("word/document.xml"));
|
||||
zip.write("<document>原文</document>".getBytes(StandardCharsets.UTF_8)); zip.closeEntry();
|
||||
}
|
||||
var originals = new java.util.LinkedHashMap<String, byte[]>();
|
||||
originals.put("a.pdf", "%PDF-1.7\noriginal".getBytes(StandardCharsets.UTF_8));
|
||||
originals.put("a.doc", new byte[]{(byte)0xd0,(byte)0xcf,0x11,(byte)0xe0,(byte)0xa1,(byte)0xb1,0x1a,(byte)0xe1});
|
||||
originals.put("a.docx",docx.toByteArray());
|
||||
for (String format : java.util.List.of("png","jpg")) {
|
||||
var image = new java.awt.image.BufferedImage(2,2,java.awt.image.BufferedImage.TYPE_INT_RGB);
|
||||
var output = new java.io.ByteArrayOutputStream(); javax.imageio.ImageIO.write(image,format,output);
|
||||
originals.put("a."+format,output.toByteArray());
|
||||
}
|
||||
for (var entry : originals.entrySet()) {
|
||||
byte[] bytes=entry.getValue();String name=entry.getKey();
|
||||
String mime=name.endsWith("docx")?"application/vnd.openxmlformats-officedocument.wordprocessingml.document":name.endsWith("doc")?"application/msword":name.endsWith("png")?"image/png":name.endsWith("jpg")?"image/jpeg":"application/pdf";
|
||||
storage.validatePrivateContent(name,bytes,mime);
|
||||
String key=storage.newPrivateKey(name,bytes.length);
|
||||
storage.appendPrivate(key,0,bytes,bytes.length);
|
||||
storage.appendPrivate(key,0,bytes,bytes.length);
|
||||
String sha=java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
assertArrayEquals(bytes,storage.readPrivate(key,bytes.length,sha));
|
||||
assertThrows(java.io.IOException.class,()->storage.readPrivate(key,bytes.length,"0".repeat(64)));
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void acceptsPrivateWordSignatureButRejectsSpoofedWord() {
|
||||
DataGovLocalFileStorage storage = new DataGovLocalFileStorage(true, root.toString(), 1024);
|
||||
storage.validatePrivateContent("原文件.doc",new byte[]{(byte)0xd0,(byte)0xcf,0x11,(byte)0xe0,(byte)0xa1,(byte)0xb1,0x1a,(byte)0xe1},"application/msword");
|
||||
assertThrows(IllegalArgumentException.class,()->storage.validatePrivateContent("假文件.doc","not word".getBytes(StandardCharsets.UTF_8),"application/msword"));
|
||||
}
|
||||
|
||||
@TempDir
|
||||
Path root;
|
||||
|
||||
@Test
|
||||
void storesReadsAndDeletesAllowedFile() throws Exception {
|
||||
DataGovLocalFileStorage storage = new DataGovLocalFileStorage(true, root.toString(), 1024);
|
||||
storage.initialize();
|
||||
byte[] content = "M0 file smoke".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
DataGovLocalFileStorage.StoredFile stored = storage.store(
|
||||
new MockMultipartFile("file", "evidence.txt", "text/plain", content)
|
||||
);
|
||||
|
||||
assertArrayEquals(content, storage.read(stored.key()));
|
||||
assertEquals("text/plain", stored.contentType());
|
||||
storage.delete(stored.key());
|
||||
assertThrows(Exception.class, () -> storage.read(stored.key()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsExecutableAndEscapingPaths() throws Exception {
|
||||
DataGovLocalFileStorage storage = new DataGovLocalFileStorage(true, root.toString(), 1024);
|
||||
storage.initialize();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> storage.store(
|
||||
new MockMultipartFile("file", "payload.sh", "text/x-shellscript", "echo unsafe".getBytes(StandardCharsets.UTF_8))
|
||||
));
|
||||
assertThrows(IllegalArgumentException.class, () -> storage.read("../outside.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsContentThatDoesNotMatchItsSuffix() throws Exception {
|
||||
DataGovLocalFileStorage storage = new DataGovLocalFileStorage(true, root.toString(), 1024);
|
||||
storage.initialize();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> storage.store(
|
||||
new MockMultipartFile("file", "spoofed.png", "image/png", "not a png".getBytes(StandardCharsets.UTF_8))
|
||||
));
|
||||
assertThrows(IllegalArgumentException.class, () -> storage.store(
|
||||
new MockMultipartFile("file", "binary.txt", "text/plain", new byte[]{'a', 0, 'b'})
|
||||
));
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class KnowledgeArchiveSafetyTest {
|
||||
@Test void acceptsPlainSkillAndReferences() { assertDoesNotThrow(()->KnowledgeArchiveSafety.check(zip(Map.of("SKILL.md","skill","refs/a.md","reference")),false)); }
|
||||
@Test void acceptsWordDocumentOnlyAsDocx() { byte[] value=zip(Map.of("word/document.xml","<document/>")); assertDoesNotThrow(()->KnowledgeArchiveSafety.check(value,true)); assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(value,false)); }
|
||||
@Test void rejectsPathTraversal() { assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(zip(Map.of("SKILL.md","skill","../escape.md","bad")),false)); }
|
||||
@Test void rejectsExecutableDependency() { assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(zip(Map.of("SKILL.md","skill","scripts/run.sh","bad")),false)); }
|
||||
@Test void rejectsMacroDocument() { assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(zip(Map.of("word/document.xml","<document/>","word/vbaProject.bin","bad")),true)); }
|
||||
@Test void rejectsHighlyCompressedPayload() { assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(zip(Map.of("SKILL.md","a".repeat(1_100_000))),false)); }
|
||||
@Test void rejectsMissingRootSkillAndInvalidZip() { assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(zip(Map.of("folder/SKILL.md","a")),false)); assertThrows(IllegalArgumentException.class,()->KnowledgeArchiveSafety.check(new byte[]{1,2,3,4},false)); }
|
||||
private byte[] zip(Map<String,String> entries) { try { var bytes=new ByteArrayOutputStream();try(var zip=new ZipOutputStream(bytes)) { for(var entry:entries.entrySet()) {zip.putNextEntry(new ZipEntry(entry.getKey()));zip.write(entry.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8));zip.closeEntry();}}return bytes.toByteArray(); } catch(Exception e) {throw new IllegalStateException(e);} }
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import java.nio.file.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class KnowledgePrivateStorageTest {
|
||||
@TempDir Path root;
|
||||
@BeforeEach void resolvePlatformTemporaryDirectory() throws Exception { root=root.toRealPath(); }
|
||||
@Test void exactPrivateOriginalCanBeErasedWithoutTouchingPublicFile() throws Exception {
|
||||
var storage=new DataGovLocalFileStorage(true,root.toString(),1024);storage.initialize();byte[] text="knowledge".getBytes(StandardCharsets.UTF_8);String key=storage.newPrivateKey("SKILL.md",text.length);storage.appendPrivate(key,0,text,text.length);storage.validatePrivateContent("SKILL.md",text,"text/markdown");
|
||||
var publicFile=storage.store(new MockMultipartFile("file","ordinary.txt","text/plain",text));
|
||||
assertArrayEquals(text,storage.readPrivate(key,text.length,HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text))));
|
||||
assertThrows(IllegalArgumentException.class,()->storage.read(key));storage.erasePrivateKnowledge(key);assertFalse(Files.exists(root.resolve(key)));assertArrayEquals(text,storage.read(publicFile.key()));assertDoesNotThrow(()->storage.erasePrivateKnowledge(key));
|
||||
}
|
||||
@Test void privateEraseRejectsPublicAndEscapingKeys() throws Exception {
|
||||
var storage=new DataGovLocalFileStorage(true,root.toString(),1024);storage.initialize();
|
||||
assertThrows(Exception.class,()->storage.erasePrivateKnowledge("ordinary.txt"));assertThrows(Exception.class,()->storage.erasePrivateKnowledge("../private-00000000-0000-4000-8000-000000000001.md"));
|
||||
}
|
||||
@Test void privateEraseDoesNotFollowSymbolicLinks() throws Exception {
|
||||
var storage=new DataGovLocalFileStorage(true,root.toString(),1024);storage.initialize();var retained=root.resolve("retained.txt");Files.writeString(retained,"retained");String key="private-00000000-0000-4000-8000-000000000001.md";Files.createSymbolicLink(root.resolve(key),retained);
|
||||
assertThrows(Exception.class,()->storage.erasePrivateKnowledge(key));assertEquals("retained",Files.readString(retained));
|
||||
}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户