Compare commits

..

No commits in common. 'main' and 'zyt_branch' have entirely different histories.

8
.idea/.gitignore vendored

@ -1,8 +0,0 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxProjectSettings">
<option name="commitMessageIssueKeyValidationOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
<option name="commitMessageValidationEnabledOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
</component>
</project>

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="22" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.8.9</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-system</artifactId>
<description>
system系统模块
</description>
<dependencies>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
</dependencies>
</project>

@ -1,39 +0,0 @@
package com.ruoyi.system.Enum;
/**
* @author: Larry
* @Date: 2023 /12 /06 / 15:23
* @Description:
*/
public enum VideoTagEnum {
ACTION(1, "鬼畜"),
COMEDY(2, "色情"),
DRAMA(3, "运动"),
ROMANCE(4, "火影忍者");
private int id;
private String type;
VideoTagEnum(int id, String type) {
this.id = id;
this.type = type;
}
public int getId() {
return id;
}
public String getType() {
return type;
}
public static VideoTagEnum getById(int id) {
for (VideoTagEnum tag : values()) {
if (tag.getId() == id) {
return tag;
}
}
throw new IllegalArgumentException("Invalid VideoTagEnum id: " + id);
}
}

@ -1,40 +0,0 @@
package com.ruoyi.system.Interceptor;
import com.zy.util.BaseContext;
import com.zy.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author: Larry
* @Date: 2023 /11 /22 / 21:40
* @Description:
*/
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Resource
RedisTemplate<String,String> redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
log.info(token);
Long userId = TokenUtil.verifyToken(token);
if (userId > 0) {
BaseContext.setCurrentId(userId);
Date passTime = TokenUtil.getTokenExpirationTime(token);
log.info(passTime.toString());
redisTemplate.opsForValue().set("token"+userId,passTime.toString(),1, TimeUnit.HOURS);
return true;
}
return false;
}
}

@ -1,32 +0,0 @@
package com.ruoyi.system.Interceptor;
import com.zy.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author: Larry
* @Date: 2023 /11 /23 / 8:40
* @Description:
*/
@Component
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
try {
Long id = TokenUtil.verifyToken(token);
TokenUtil.generateRefreshToken(id);
log.info("刷新成功");
return true ;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

@ -1,7 +0,0 @@
package demo1;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("HelloWorld");
}
}

@ -1,4 +0,0 @@
/**
* api XxxPort domain
*/
package com.ruoyi.system.adapter.port;

@ -1,81 +0,0 @@
package com.ruoyi.system.adapter.repository;
import cn.bugstack.domain.activity.adapter.repository.IActivityRepository;
import cn.bugstack.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.bugstack.domain.activity.model.valobj.SkuVO;
import cn.bugstack.infrastructure.dao.IGroupBuyActivityDao;
import cn.bugstack.infrastructure.dao.IGroupBuyDiscountDao;
import cn.bugstack.infrastructure.dao.ISkuDao;
import cn.bugstack.infrastructure.dao.po.GroupBuyActivity;
import cn.bugstack.infrastructure.dao.po.GroupBuyDiscount;
import cn.bugstack.infrastructure.dao.po.Sku;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-12-21 10:10
*/
@Repository
public class ActivityRepository implements IActivityRepository {
@Resource
private IGroupBuyActivityDao groupBuyActivityDao;
@Resource
private IGroupBuyDiscountDao groupBuyDiscountDao;
@Resource
private ISkuDao skuDao;
@Override
public GroupBuyActivityDiscountVO queryGroupBuyActivityDiscountVO(String source, String channel) {
// 根据SC渠道值查询配置中最新的1个有效的活动
GroupBuyActivity groupBuyActivityReq = new GroupBuyActivity();
groupBuyActivityReq.setSource(source);
groupBuyActivityReq.setChannel(channel);
GroupBuyActivity groupBuyActivityRes = groupBuyActivityDao.queryValidGroupBuyActivity(groupBuyActivityReq);
String discountId = groupBuyActivityRes.getDiscountId();
GroupBuyDiscount groupBuyDiscountRes = groupBuyDiscountDao.queryGroupBuyActivityDiscountByDiscountId(discountId);
GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = GroupBuyActivityDiscountVO.GroupBuyDiscount.builder()
.discountName(groupBuyDiscountRes.getDiscountName())
.discountDesc(groupBuyDiscountRes.getDiscountDesc())
.discountType(groupBuyDiscountRes.getDiscountType())
.marketPlan(groupBuyDiscountRes.getMarketPlan())
.marketExpr(groupBuyDiscountRes.getMarketExpr())
.tagId(groupBuyDiscountRes.getTagId())
.build();
return GroupBuyActivityDiscountVO.builder()
.activityId(groupBuyActivityRes.getActivityId())
.activityName(groupBuyActivityRes.getActivityName())
.source(groupBuyActivityRes.getSource())
.channel(groupBuyActivityRes.getChannel())
.goodsId(groupBuyActivityRes.getGoodsId())
.groupBuyDiscount(groupBuyDiscount)
.groupType(groupBuyActivityRes.getGroupType())
.takeLimitCount(groupBuyActivityRes.getTakeLimitCount())
.target(groupBuyActivityRes.getTarget())
.validTime(groupBuyActivityRes.getValidTime())
.status(groupBuyActivityRes.getStatus())
.startTime(groupBuyActivityRes.getStartTime())
.endTime(groupBuyActivityRes.getEndTime())
.tagId(groupBuyActivityRes.getTagId())
.tagScope(groupBuyActivityRes.getTagScope())
.build();
}
@Override
public SkuVO querySkuByGoodsId(String goodsId) {
Sku sku = skuDao.querySkuByGoodsId(goodsId);
return SkuVO.builder()
.goodsId(sku.getGoodsId())
.goodsName(sku.getGoodsName())
.originalPrice(sku.getOriginalPrice())
.build();
}
}

@ -1,4 +0,0 @@
/**
* domain IXxxRepository Repository
*/
package com.ruoyi.system.adapter.repository;

@ -1,18 +0,0 @@
package com.ruoyi.system.ai.annotation;
import com.muta.ai.chain.DefaultChainFactory;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author: Larry
* @Date: 2024 /05 /01 / 0:10
* @Description:
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogicStrategy {
DefaultChainFactory.LogicModel logicMode();
}

@ -1,30 +0,0 @@
package com.ruoyi.system.ai.chain;
import com.muta.ai.domain.RuleLogicEntity;
import lombok.extern.slf4j.Slf4j;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 09:37
*/
@Slf4j
public abstract class AbstractLogicChain implements ILogicChain<UserAccountQuotaEntity> {
private ILogicChain<UserAccountQuotaEntity> next;
@Override
public ILogicChain<UserAccountQuotaEntity> next() {
return next;
}
@Override
public ILogicChain<UserAccountQuotaEntity> appendNext(ILogicChain<UserAccountQuotaEntity> next) {
this.next = next;
return next;
}
protected abstract String ruleModel();
public abstract RuleLogicEntity<MusicProcessAggregate> logic(UserAccountQuotaEntity userAccountQuotaEntity, MusicProcessAggregate chatProcessAggregate);
}

@ -1,36 +0,0 @@
package com.ruoyi.system.ai.chain;
import com.muta.ai.annotation.LogicStrategy;
import com.muta.ai.chain.MusicProcessAggregate;
import com.muta.ai.domain.RuleLogicEntity;
import com.muta.ai.chain.UserAccountQuotaEntity;
import com.muta.ai.chain.DefaultChainFactory;
import com.muta.ai.chain.AbstractLogicChain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 10:23
*/
@Slf4j
@Component("rule_blacklist")
@LogicStrategy(logicMode = DefaultChainFactory.LogicModel.RULE_BLACKLIST)
public class BackListLogicChain extends AbstractLogicChain {
;
@Override
protected String ruleModel() {
return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
}
@Override
public RuleLogicEntity<MusicProcessAggregate> logic(UserAccountQuotaEntity userAccountQuotaEntity, MusicProcessAggregate chatProcessAggregate) {
return null;
}
}

@ -1,70 +0,0 @@
package com.ruoyi.system.ai.chain;
import com.muta.ai.annotation.LogicStrategy;
import lombok.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 10:54
*/
@Service
public class DefaultChainFactory {
public Map<String, ILogicChain<UserAccountQuotaEntity>> logicFilterMap = new ConcurrentHashMap<>();
public DefaultChainFactory(List<ILogicChain<UserAccountQuotaEntity>> logicFilters) {
logicFilters.forEach(logic -> {
LogicStrategy strategy = AnnotationUtils.findAnnotation(logic.getClass(), LogicStrategy.class);
if (null != strategy) {
logicFilterMap.put(strategy.logicMode().getCode(), logic);
}
});
}
/**
* ID
* @return LogicChain
*/
public ILogicChain<UserAccountQuotaEntity> openLogicChain(Long test) {
List<String> ruleModels = new ArrayList<>();
ruleModels.add(LogicModel.RULE_BLACKLIST.code);
ruleModels.add(LogicModel.RULE_WEIGHT.code);
ILogicChain<UserAccountQuotaEntity> current = logicFilterMap.get(LogicModel.RULE_BLACKLIST.getCode());
System.out.println(current+"current");
for (int i = 1; i < ruleModels.size(); i++) {
System.out.println(ruleModels.get(i));
ILogicChain<UserAccountQuotaEntity> nextChain = logicFilterMap.get(ruleModels.get(i));
System.out.println(nextChain);
current = current.appendNext(nextChain);
}
current.appendNext(logicFilterMap.get(LogicModel.RULE_DEFAULT.code));
return current;
}
@Getter
@AllArgsConstructor
public enum LogicModel {
RULE_DEFAULT("rule_default", "默认抽奖"),
RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
RULE_WEIGHT("rule_weight", "权重规则"),
RULE_SENSITIVE_WORDS("rule_sensitive_words", "敏感词规则过滤"),
RULE_SING("rule_sing", "歌曲过滤"),
;
private final String code;
private final String info;
}
}

@ -1,35 +0,0 @@
package com.ruoyi.system.ai.chain;
import com.muta.ai.annotation.LogicStrategy;
import com.muta.ai.chain.MusicProcessAggregate;
import com.muta.ai.domain.RuleLogicEntity;
import com.muta.ai.chain.UserAccountQuotaEntity;
import com.muta.ai.chain.DefaultChainFactory;
import com.muta.ai.chain.AbstractLogicChain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 10:06
*/
@Slf4j
@Component("rule_default")
@LogicStrategy(logicMode = DefaultChainFactory.LogicModel.RULE_DEFAULT)
public class DefaultLogicChain extends AbstractLogicChain {
@Override
protected String ruleModel() {
return DefaultChainFactory.LogicModel.RULE_DEFAULT.getCode();
}
@Override
public RuleLogicEntity<MusicProcessAggregate> logic(UserAccountQuotaEntity userAccountQuotaEntity, MusicProcessAggregate chatProcessAggregate) {
System.out.println("测试注入");
return null;
}
}

@ -1,17 +0,0 @@
package com.ruoyi.system.ai.chain;
import com.muta.ai.domain.RuleLogicEntity;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 09:40
*/
public interface ILogicChain<T> extends ILogicChainArmory<T>, Cloneable {
/**
*
*/
RuleLogicEntity<MusicProcessAggregate> logic(UserAccountQuotaEntity userAccountQuotaEntity, MusicProcessAggregate data);
}

@ -1,14 +0,0 @@
package com.ruoyi.system.ai.chain;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 11:53
*/
public interface ILogicChainArmory<T> {
ILogicChain<T> next();
ILogicChain<T> appendNext(ILogicChain<T> next);
}

@ -1,30 +0,0 @@
package com.ruoyi.system.ai.chain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2023-07-22 21:09
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MusicProcessAggregate {
/**
* ID
*/
private Long singerId;
/**
* ID
*/
private Integer musicId;
/** 提示词 */
private String prompt;
}

@ -1,40 +0,0 @@
package com.ruoyi.system.ai.chain;
import com.muta.ai.annotation.LogicStrategy;
import com.muta.ai.chain.MusicProcessAggregate;
import com.muta.ai.domain.RuleLogicEntity;
import com.muta.ai.chain.UserAccountQuotaEntity;
import com.muta.ai.chain.DefaultChainFactory;
import com.muta.ai.chain.AbstractLogicChain;
import com.muta.system.service.IUserExtraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2024-01-20 10:38
*/
@Slf4j
@Component("rule_UserAccountQuota")
@LogicStrategy(logicMode = DefaultChainFactory.LogicModel.RULE_WEIGHT)
public class RuleWeightLogicChain extends AbstractLogicChain {
@Resource
private IUserExtraService userExtraService;
@Override
protected String ruleModel() {
return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
}
@Override
public RuleLogicEntity<MusicProcessAggregate> logic(UserAccountQuotaEntity userAccountQuotaEntity, MusicProcessAggregate chatProcessAggregate) {
return null;
}
}

@ -1,36 +0,0 @@
package com.ruoyi.system.ai.chain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Arrays;
import java.util.List;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2023-10-03 16:49
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UserAccountQuotaEntity {
/**
* ID
*/
private Long userId;
/**
*
*/
private Integer integral;
/**
*
*/
private Integer vipGrade;
}

@ -1,24 +0,0 @@
package com.ruoyi.system.ai.config;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author: Larry
* @Date: 2024 /05 /11 / 14:18
* @Description:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ChatConfig {
private Long id;
private Long userId;
private float temperature;
private Integer maxToken;
private Integer n;
private float top;
}

@ -1,32 +0,0 @@
package com.ruoyi.system.ai.config;
import com.github.houbb.sensitive.word.api.IWordAllow;
import org.apache.commons.compress.utils.Lists;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author Larry
* @date 2024-05-18 15:07:01
*/
public class CustomWordAllow implements IWordAllow {
/**
* -
*
* @return
*/
@Override
public List<String> allow() {
// 可以获取数据库数据或文件内容
List<String> list = new ArrayList<>();
list.add("草");
list.add("小草");
list.add("");
return list;
}
}

@ -1,30 +0,0 @@
package com.ruoyi.system.ai.config;
import com.github.houbb.sensitive.word.api.IWordDeny;
import org.apache.commons.compress.utils.Lists;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author Larry
* @date 2024-05-08 14:59:51
*/
public class CustomWordDeny implements IWordDeny {
/**
* -
*
* @return
*/
@Override
public List<String> deny() {
// 可以获取数据库数据或文件内容
List<String> list = new ArrayList<>();
list.add("测试");
return list;
}
}

@ -1,70 +0,0 @@
package com.ruoyi.system.ai.config;//package com.muta.ai.config;
//
//import com.muta.ai.chain.UserAccountQuotaEntity;
//import com.muta.ai.service.ILogicFilter;
//import com.muta.ai.service.impl.SensitiveWordFilter;
//import com.muta.ai.service.impl.TokenFilter;
//import com.muta.ai.service.impl.UserQuotaFilter;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//
///**
// * @author: Larry
// * @Date: 2024 /05 /09 / 20:35
// * @Description:
// */
//public class LogicConfig {
// public Map<String, ILogicFilter<UserAccountQuotaEntity>> logicFilterMap = new ConcurrentHashMap<>();
// @Resource
// private SensitiveWordFilter sensitiveWordFilter;
// @Resource
// private TokenFilter tokenFilter;
// @Resource
// private UserQuotaFilter userQuotaFilter;
// @PostConstruct
// private void init(){
// logicFilterMap.put(LogicModel.SENSITIVE_WORD.code,sensitiveWordFilter);
// logicFilterMap.put(LogicModel.MAX_TOKEN.code,tokenFilter);
// logicFilterMap.put(LogicModel.USER_QUOTA.code, userQuotaFilter);
//
// }
// public enum LogicModel {
//
// NULL("NULL", "放行不用过滤"),
// MAX_TOKEN("TOKEN_LIMIT", "限制最大会话数"),
// SENSITIVE_WORD("SENSITIVE_WORD", "敏感词过滤"),
// USER_QUOTA("USER_QUOTA", "用户额度过滤"),
//// MODEL_TYPE("MODEL_TYPE", "模型可用范围过滤"),
//// ACCOUNT_STATUS("ACCOUNT_STATUS", "账户状态过滤"),
//
// ;
//
// private String code;
// private String info;
//
// LogicModel(String code, String info) {
// this.code = code;
// this.info = info;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
// }
//
//}

@ -1,85 +0,0 @@
package com.ruoyi.system.ai.config;
import lombok.Data;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.annotation.Resource;
/**
* @ClassName RabbitMQConfig
* @Author Larr
* @create 2024/5/12 15:23
*/
@Configuration
@Data
public class MessageMqConfig {
/**
*
*/
@Value("${mqconfig.message_event_exchange}")
private String eventExchange;
/**
*
*/
@Value("${mqconfig.message_queue}")
private String MessageQueue;
/**
* key
* key
*/
@Value("${mqconfig.message_routing_key}")
private String MessageRoutingKey;
/**
*
*/
@Value("${mqconfig.ttl}")
private Integer ttl;
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
return rabbitTemplate;
}
@Bean
public Exchange MessageEventExchange() {
return new TopicExchange(eventExchange, true, false);
}
@Bean
public Queue MessageQueue() {
return new Queue(MessageQueue, true, false, false);
}
@Bean
public Binding couponRelaseBinding() {
return new Binding(MessageQueue, Binding.DestinationType.QUEUE, eventExchange, MessageRoutingKey, null);
}
/**
* @Author Administrator
*
**/
// @Bean
// public Queue couponReleaseDelayQueue() {
// Map<String, Object> args = new HashMap<>(3);
// args.put("x-message-ttl", ttl);
// args.put("x-dead-letter-routing-key", couponReleaseRoutingKey);
// args.put("x-dead-letter-exchange", eventExchange);
// return new Queue(couponReleaseDelayQueue, true, false, false, args);
// }
}

@ -1,30 +0,0 @@
package com.ruoyi.system.ai.config;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
*
* @author
* @date 2023-09-08 14:28:45
*/
@Configuration
public class SensitiveWordConfig {
/**
*
*
* @return
* @since 1.0.0
*/
@Bean(value = "sensitiveWordBsBean")
public SensitiveWordBs sensitiveWordBs() {
System.out.println("测试");
// 设置系统默认敏感词
return SensitiveWordBs.newInstance().wordDeny(new CustomWordDeny()).wordAllow(new CustomWordAllow()).init();
}
}

@ -1,34 +0,0 @@
package com.ruoyi.system.ai.config;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.util.WebAppRootListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* @author Frankiefly
* 2024/3/23
*/
@Configuration
public class WebSocketConfiguration implements ServletContextInitializer {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(WebAppRootListener.class);
//这里设置了1024M的缓冲区
//Tomcat每次请求过来时在创建session时都会把这个webSocketContainer作为参数传进去所以对所有的session都生效了
servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize","1024000");
}
}

@ -1,524 +0,0 @@
package com.ruoyi.system.ai.config.server;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.Gson;
import com.muta.ai.domain.ChatCompletionMessage;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import netscape.javascript.JSObject;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class Client {
private static final String DEFAULT_BASE_URL = "https://api.moonshot.cn/v1";
private static final String CHAT_COMPLETION_SUFFIX = "/chat/completions";
private static final String MODELS_SUFFIX = "/models";
private static final String FILES_SUFFIX = "/files";
private String baseUrl;
private String apiKey;
public Client(String apiKey) {
this(apiKey, DEFAULT_BASE_URL);
}
public Client(String apiKey, String baseUrl) {
this.apiKey = apiKey;
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
this.baseUrl = baseUrl;
}
public String getChatCompletionUrl() {
return baseUrl + CHAT_COMPLETION_SUFFIX;
}
public String getModelsUrl() {
return baseUrl + MODELS_SUFFIX;
}
public String getFilesUrl() {
return baseUrl + FILES_SUFFIX;
}
public String getApiKey() {
return apiKey;
}
public ModelsList ListModels() throws IOException {
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(getModelsUrl())
.addHeader("Authorization", "Bearer " + getApiKey())
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
String body = response.body().string();
Gson gson = new Gson();
return gson.fromJson(body, ModelsList.class);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
public ChatCompletionResponse ChatCompletion(ChatCompletionRequest request) throws IOException {
request.stream = false;
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, new Gson().toJson(request));
okhttp3.Request httpRequest = new okhttp3.Request.Builder()
.url(getChatCompletionUrl())
.addHeader("Authorization", "Bearer " + getApiKey())
.addHeader("Content-Type", "application/json")
.post(body)
.build();
try {
okhttp3.Response response = client.newCall(httpRequest).execute();
String responseBody = response.body().string();
System.out.println(responseBody);
Gson gson = new Gson();
return gson.fromJson(responseBody, ChatCompletionResponse.class);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
// return a stream of ChatCompletionStreamResponse
public Flowable<ChatCompletionStreamResponse> ChatCompletionStream(ChatCompletionRequest request) throws IOException {
request.stream = true;
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, new Gson().toJson(request));
okhttp3.Request httpRequest = new okhttp3.Request.Builder()
.url(getChatCompletionUrl())
.addHeader("Authorization", "Bearer " + getApiKey())
.addHeader("Content-Type", "application/json")
.post(body)
.build();
okhttp3.Response response = client.newCall(httpRequest).execute();
if (response.code() != 200) {
System.err.println(response);
throw new RuntimeException("Failed to start stream: " + response.body().string());
}
// get response body line by line
return Flowable.create(emitter -> {
okhttp3.ResponseBody responseBody = response.body();
if (responseBody == null) {
emitter.onError(new RuntimeException("Response body is null"));
return;
}
String line;
while ((line = responseBody.source().readUtf8Line()) != null) {
if (line.startsWith("data:")) {
line = line.substring(5);
line = line.trim();
}
if (Objects.equals(line, "[DONE]")) {
emitter.onComplete();
return;
}
line = line.trim();
if (line.isEmpty()) {
continue;
}
//System.out.println(line);
Gson gson = new Gson();
ChatCompletionStreamResponse streamResponse = gson.fromJson(line, ChatCompletionStreamResponse.class);
emitter.onNext(streamResponse);
}
emitter.onComplete();
}, BackpressureStrategy.BUFFER);
}
}
enum ChatMessageRole {
SYSTEM, USER, ASSISTANT;
public String value() {
return this.name().toLowerCase();
}
}
class ChatCompletionStreamChoiceDelta {
private String content;
private String role;
public String getContent() {
return content;
}
public String getRole() {
return role;
}
public void setContent(String content) {
this.content = content;
}
public void setRole(String role) {
this.role = role;
}
public ChatCompletionStreamChoiceDelta(String content, String role) {
this.content = content;
this.role = role;
}
@Override
public String toString() {
return "ChatCompletionStreamChoiceDelta{" +
"content='" + content + '\'' +
", role='" + role + '\'' +
'}';
}
}
class Usage {
private int prompt_tokens;
private int completion_tokens;
private int total_tokens;
public int getPrompt_tokens() {
return prompt_tokens;
}
public void setPrompt_tokens(int prompt_tokens) {
this.prompt_tokens = prompt_tokens;
}
public int getCompletion_tokens() {
return completion_tokens;
}
public void setCompletion_tokens(int completion_tokens) {
this.completion_tokens = completion_tokens;
}
public int getTotal_tokens() {
return total_tokens;
}
public void setTotal_tokens(int total_tokens) {
this.total_tokens = total_tokens;
}
public Usage(int prompt_tokens, int completion_tokens, int total_tokens) {
this.prompt_tokens = prompt_tokens;
this.completion_tokens = completion_tokens;
this.total_tokens = total_tokens;
}
public Usage() {
}
@Override
public String toString() {
return "Usage{" +
"prompt_tokens=" + prompt_tokens +
", completion_tokens=" + completion_tokens +
", total_tokens=" + total_tokens +
'}';
}
}
class ChatCompletionStreamChoice {
private int index;
private ChatCompletionStreamChoiceDelta delta;
@SerializedName("finish_reason")
private String finishReason;
private Usage usage;
public int getIndex() {
return index;
}
public ChatCompletionStreamChoiceDelta getDelta() {
return delta;
}
public String getFinishReason() {
return finishReason;
}
public Usage getUsage() {
return usage;
}
public void setIndex(int index) {
this.index = index;
}
public void setDelta(ChatCompletionStreamChoiceDelta delta) {
this.delta = delta;
}
public void setFinishReason(String finishReason) {
this.finishReason = finishReason;
}
public void setUsage(Usage usage) {
this.usage = usage;
}
public ChatCompletionStreamChoice(int index, ChatCompletionStreamChoiceDelta delta, String finishReason, Usage usage) {
this.index = index;
this.delta = delta;
this.finishReason = finishReason;
this.usage = usage;
}
@Override
public String toString() {
return "ChatCompletionStreamChoice{" +
"index=" + index +
", delta=" + delta +
", finishReason='" + finishReason + '\'' +
", usage=" + usage +
'}';
}
}
class ChatCompletionStreamResponse {
private String id;
private String object;
private long created;
private String model;
private List<ChatCompletionStreamChoice> choices;
public String getId() {
return id;
}
public String getObject() {
return object;
}
public long getCreated() {
return created;
}
public String getModel() {
return model;
}
public List<ChatCompletionStreamChoice> getChoices() {
return choices;
}
public void setId(String id) {
this.id = id;
}
public void setObject(String object) {
this.object = object;
}
public void setCreated(long created) {
this.created = created;
}
@Override
public String toString() {
return "ChatCompletionStreamResponse{" +
"id='" + id + '\'' +
", object='" + object + '\'' +
", created=" + created +
", model='" + model + '\'' +
", choices=" + choices +
'}';
}
}
class ChatCompletionChoice {
private int index;
private ChatCompletionMessage message;
@SerializedName("finish_reason")
private String finishReason;
public int getIndex() {
return index;
}
public ChatCompletionMessage getMessage() {
return message;
}
public String getFinishReason() {
return finishReason;
}
public void setIndex(int index) {
this.index = index;
}
public void setMessage(ChatCompletionMessage message) {
this.message = message;
}
public void setFinishReason(String finishReason) {
this.finishReason = finishReason;
}
}
class ChatCompletionResponse {
private String id;
private String object;
private long created;
private String model;
private List<ChatCompletionChoice> choices;
private Usage usage;
public String getId() {
return id;
}
public String getObject() {
return object;
}
public long getCreated() {
return created;
}
public String getModel() {
return model;
}
public List<ChatCompletionChoice> getChoices() {
if (choices == null) {
return List.of();
}
return choices;
}
}
class ChatCompletionRequest {
public String model;
public List<ChatCompletionMessage> messages;
@SerializedName("max_tokens")
public int maxTokens;
@SerializedName("temperature")
public float temperature;
public float topP;
public Integer n;
public boolean stream;
public List<String> stop;
@SerializedName("presence_penalty")
public float presencePenalty;
@SerializedName("frequency_penalty")
public float frequencyPenalty;
public String user;
public List<ChatCompletionMessage> getMessages() {
return messages;
}
public ChatCompletionRequest(String model, List<ChatCompletionMessage> messages, int maxTokens, float temperature, int n, float topP) {
this.model = model;
this.messages = messages;
this.maxTokens = maxTokens;
this.temperature = temperature;
this.n = n;
this.topP = topP;
}
}
class Model {
private String id;
private String object;
@SerializedName("owner_by")
private String ownedBy;
private String root;
private String parent;
public String getId() {
return id;
}
public String getObject() {
return object;
}
public String getOwnedBy() {
return ownedBy;
}
public String getRoot() {
return root;
}
public String getParent() {
return parent;
}
public void setId(String id) {
this.id = id;
}
public void setObject(String object) {
this.object = object;
}
public void setOwnedBy(String ownedBy) {
this.ownedBy = ownedBy;
}
public void setRoot(String root) {
this.root = root;
}
public void setParent(String parent) {
this.parent = parent;
}
public Model(String id, String object, String ownedBy, String root, String parent) {
this.id = id;
this.object = object;
this.ownedBy = ownedBy;
this.root = root;
this.parent = parent;
}
}
class ModelsList {
private List<Model> data;
public List<Model> getData() {
return data;
}
public void setData(List<Model> data) {
this.data = data;
}
public ModelsList(List<Model> data) {
this.data = data;
}
}

@ -1,187 +0,0 @@
package com.ruoyi.system.ai.config.server;
import cn.hutool.core.collection.CollectionUtil;
import com.muta.ai.chain.MusicProcessAggregate;
import com.muta.ai.chain.UserAccountQuotaEntity;
import com.muta.ai.config.ChatConfig;
import com.muta.ai.domain.*;
import com.muta.ai.enums.LogicCheckEnum;
import com.muta.ai.service.IChatConfigService;
import com.muta.ai.service.IMessageFileService;
import com.muta.ai.service.impl.KimiChatService;
import com.muta.common.utils.StringUtils;
import org.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
@Component
@ServerEndpoint(value = "/chatgpt/{sid}")
public class WebSocketServer {
private static IChatConfigService chatConfigService;
private static RedisTemplate<String, ChatCompletionMessage> redisTemplate;
private static KimiChatService kimiChatService;
private static IMessageFileService messageFileService;
@Resource
public void setChatConfigService(IChatConfigService chatConfigService) {
WebSocketServer.chatConfigService = chatConfigService;
}
@Resource
public void setMessageFileService(IMessageFileService messageFileService) {
WebSocketServer.messageFileService = messageFileService;
}
@Resource
public void setKimiChatService(KimiChatService kimiChatService) {
WebSocketServer.kimiChatService = kimiChatService;
}
@Resource
public void setChatgptService(RedisTemplate redisTemplate) {
WebSocketServer.redisTemplate = redisTemplate;
}
private static Map<String, Session> sessionMap = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
System.out.println("客户端: " + sid + "建立连接");
sessionMap.put(sid, session);
}
@OnMessage
public void onMessage(String jsonFrom, @PathParam("sid") String sid) throws Exception {
JSONObject jsonParse = new JSONObject(jsonFrom);
String url = jsonFrom.contains("\"url\"") ? jsonParse.getString("url") : null;
String content = jsonParse.getString("content");
String model = jsonParse.getString("model");
if (StringUtils.isNotEmpty(url)) {
content += " " + messageFileService.getContentByUrl(url);
}
Long userId = Long.valueOf(sid.split(":")[0]);
List<ChatCompletionMessage> history = redisTemplate.opsForSet().members(sid).stream().collect(Collectors.toList());
List<ChatCompletionMessage> messages = CollectionUtil.isEmpty(history) ? new ArrayList<>() : history;
messages.add(new ChatCompletionMessage(ChatMessageRole.USER.value(), content));
for (ChatCompletionMessage message : messages) {
System.out.println(message.toString());
}
MusicProcessAggregate chatProcessAggregate = kimiChatService.initChatData(userId, model, messages);
System.out.println(chatProcessAggregate.toString());
UserAccountQuotaEntity userAccountQuotaEntity = kimiChatService.initUserData(userId);
System.out.println(userAccountQuotaEntity.toString());
//
RuleLogicEntity<MusicProcessAggregate> logicRes = kimiChatService.doCheckLogic(chatProcessAggregate, userAccountQuotaEntity);
if(logicRes.getType().equals(LogicCheckEnum.REFUSE)){
sendToClient(sid, logicRes.getInfo());
}
else {
System.err.println(chatProcessAggregate.getKey());
Client client = new Client(chatProcessAggregate.getKey());
StringBuffer stringBuffer = new StringBuffer();
AtomicBoolean flag = new AtomicBoolean(true);
AtomicReference<String> role = new AtomicReference<>();
ChatConfig config = chatConfigService.selectChatConfigById(userId);
try {
String finalContent = content;
client.ChatCompletionStream(new ChatCompletionRequest(
model,
messages,
userAccountQuotaEntity.getMaxToken(),
config.getTemperature(),
config.getN(),
config.getTop()
)).subscribe(
streamResponse -> {
if (streamResponse.getChoices().isEmpty()) {
return;
}
for (ChatCompletionStreamChoice choice : streamResponse.getChoices()) {
if (flag.getAndSet(false)) {
role.set(choice.getDelta().getRole());
}
String finishReason = choice.getFinishReason();
System.out.println(choice.getDelta().getContent());
stringBuffer.append(choice.getDelta().getContent());
if (finishReason != null) {
System.out.println(streamResponse);
System.out.println(sid);
MessageEntity messageEntity
= MessageEntity.builder()
.model(streamResponse.getModel())
.role(role.get())
.userId(userId)
.content(stringBuffer.toString())
.finishReason(finishReason)
.promptTokens(choice.getUsage().getPrompt_tokens())
.completionTokens(choice.getUsage().getCompletion_tokens())
.totalTokens(choice.getUsage().getTotal_tokens())
.sessionId(sid)
.build();
System.out.println(messageEntity.toString());
kimiChatService.PostRule(chatProcessAggregate,userAccountQuotaEntity, messageEntity);
continue;
}
sendToClient(sid, choice.getDelta().getContent());
}
},
error -> {
error.printStackTrace();
},
() -> {
System.out.println("complete");
// redisTemplate.opsForSet().remove(sid);
// Set<ChatCompletionMessage> members = redisTemplate.opsForSet().members(sid);
// members.add(new ChatCompletionMessage(ChatMessageRole.USER.value(), finalContent));
redisTemplate.opsForSet().add(sid, new ChatCompletionMessage(ChatMessageRole.USER.value(), finalContent));
}
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@OnClose
public void onClose(@PathParam("sid") String sid){
System.out.println("连接断开: " + sid);
sessionMap.remove(sid);
}
public void sendToClient(String sid, String result){
Session session = sessionMap.get(sid);
try {
session.getBasicRemote().sendText(result);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

@ -1,50 +0,0 @@
package com.ruoyi.system.ai.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.muta.common.core.MutaBaseEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AiKey extends MutaBaseEntity {
/** 主键 */
@TableId(value = "id",type = IdType.AUTO)
private Long id;
/** key值 */
@TableField("`key`")
private String key;
/** 代理 */
@TableField("`host`")
private String host;
/** 可用模型 */
@TableField("`model_list`")
private String modelList;
/** ai类型 */
@TableField("`type`")
private Integer type;
/** 状态 */
@TableField("`status`")
private String status;
/** 额度 */
@TableField("`limit`")
private BigDecimal limit;
/** 用户id */
@TableField("`user_id`")
private Long userId;
}

@ -1,40 +0,0 @@
package com.ruoyi.system.ai.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@Builder
public class ChatCompletionMessage {
public String role;
public String name;
public String content;
public Boolean partial;
public ChatCompletionMessage(String role, String content) {
this.role = role;
this.content = content;
}
public ChatCompletionMessage(String role, String name, String content, Boolean partial) {
this.role = role;
this.name = name;
this.content = content;
this.partial = partial;
}
public String getName() {
return name;
}
public String getContent() {
return content;
}
public Boolean getPartial() {
return partial;
}
}

@ -1,26 +0,0 @@
package com.ruoyi.system.ai.domain;//package com.muta.ai.domain;
//
//import com.baomidou.mybatisplus.annotation.TableName;
//import lombok.AllArgsConstructor;
//import lombok.Builder;
//import lombok.Data;
//import lombok.NoArgsConstructor;
//
///**
// * @author: Larry
// * @Date: 2024 /05 /11 / 14:18
// * @Description:
// */
//@Data
//@AllArgsConstructor
//@NoArgsConstructor
//@Builder
//@TableName("chat_config")
//public class ChatConfig {
// private Long id;
// private Long userId;
// private float temperature;
// private String maxToken;
// private Integer n;
// private float top;
//}

@ -1,46 +0,0 @@
package com.ruoyi.system.ai.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.muta.common.core.MutaBaseEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @author: Larry
* @Date: 2024 /05 /09 / 13:17
* @Description:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MessageEntity extends MutaBaseEntity {
@TableId(type = IdType.AUTO)
private Long id;
private Long userId;
private String content;
private String role;
private String model;
private String url;
private String finishReason;
private String sessionId;
private Integer promptTokens;
private Integer completionTokens;
private Integer totalTokens;
}

@ -1,55 +0,0 @@
package com.ruoyi.system.ai.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.muta.common.core.MutaBaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @author
* @Date: 2024/05/17/14:57
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MessageFile extends MutaBaseEntity {
/**
*
*/
@TableId(type = IdType.AUTO)
@JsonFormat(shape =JsonFormat.Shape.STRING)
private Long id;
/**
*
*/
private String name;
/**
* urlurl
*/
private String url;
/**
*
*/
private String size;
/**
*
*/
private String analysisContent;
/**
* id
*/
@JsonFormat(shape =JsonFormat.Shape.STRING)
private Long messageId;
}

@ -1,35 +0,0 @@
package com.ruoyi.system.ai.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.muta.common.core.MutaBaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @author
* @Date: 2024/05/13/15:52
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MessageSession extends MutaBaseEntity {
/**
* id
*/
@TableId(type = IdType.AUTO)
@JsonFormat(shape =JsonFormat.Shape.STRING)
private Long id;
/**
* userId
*/
@JsonFormat(shape =JsonFormat.Shape.STRING)
private Long userId;
}

@ -1,23 +0,0 @@
package com.ruoyi.system.ai.domain;
import com.muta.ai.enums.LogicCheckEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2023-09-16 17:02
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RuleLogicEntity<T> {
private LogicCheckEnum type;
private String info;
private T data;
}

@ -1,26 +0,0 @@
package com.ruoyi.system.ai.domain.dto;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author: Larry
* @Date: 2024 /05 /10 / 18:41
* @Description:
*/
@NoArgsConstructor
@Data
@Builder
public class MessageHistoryKimi {
private String role;
private String content;
public MessageHistoryKimi(String role, String content) {
this.role = role;
this.content = content;
}
}

@ -1,45 +0,0 @@
package com.ruoyi.system.ai.domain.dto;
import com.muta.ai.domain.ChatCompletionMessage;
import com.muta.ai.domain.MessageEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author: Larry
* @Date: 2024 /05 /21 / 17:55
* @Description:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PostDTO {
private MessageEntity message;
/**
* ID
*/
private Long userId;
/**
*
*/
private String model;
/** 历史消息 */
private List<ChatCompletionMessage> messages;
/**
* key
*/
private String key;
/**
* key
*/
private Integer modelConsumer;
/**
* token
*/
private Integer tokenNum;
}

@ -1,31 +0,0 @@
package com.ruoyi.system.ai.domain.event;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author: Larry
* @Date: 2024 /05 /15 / 17:44
* @Description:
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class MessageEvent implements Serializable {
private static final long serialVersionUID = 3349917261877342192L;
private Long userId;
private String finishReason;
private String promptTokens;
private String completionTokens;
private Integer totalTokens;
private String content;
private String role;
private String model;
private String username;
private Long sessionId;
}

@ -1,22 +0,0 @@
package com.ruoyi.system.ai.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Larry
* @description
* @create 2024-05-06 17:04
*/
@Getter
@AllArgsConstructor
public enum LogicCheckEnum {
SUCCESS("0000", "校验通过"),
REFUSE("0001","校验拒绝"),
;
private final String code;
private final String info;
}

@ -1,8 +0,0 @@
package com.ruoyi.system.ai.enums;
public enum RoleEnum {
system,
user,
assistant;
}

@ -1,35 +0,0 @@
package com.ruoyi.system.ai.factory;//package com.muta.ai.factory;
//
//
//import com.muta.ai.annotation.LogicStrategy;
//import com.muta.ai.config.LogicConfig;
//import com.muta.ai.chain.UserAccountQuotaEntity;
//import com.muta.ai.service.ILogicFilter;
//import org.springframework.core.annotation.AnnotationUtils;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//
///**
// * @author Fuzhengwei bugstack.cn @小傅哥
// * @description 规则工厂
// * @create 2023-09-16 17:42
// */
//@Service
//public class DefaultLogicFactory extends LogicConfig {
//
// //后期可加入参数,自动选择过滤器
// public Map<String, ILogicFilter<UserAccountQuotaEntity>> openLogicFilter() {
// return logicFilterMap;
// }
//
//
// /**
// * 规则逻辑枚举
// */
//
//}

@ -1,70 +0,0 @@
package com.ruoyi.system.ai.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.muta.ai.domain.AiKey;
import com.muta.common.annotation.AutoFill;
import com.muta.common.enums.BaseOperatorType;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* Mapper
*
* @author mutaai
* @date 2024-05-16
*/
@Mapper
public interface AiKeyMapper extends BaseMapper<AiKey> {
/**
*
*
* @param id
* @return
*/
public AiKey selectAiKeyById(Long id);
/**
*
*
* @return
*/
public List<AiKey> selectAiKeyList();
/**
*
*
* @param aiKey
* @return
*/
@AutoFill(BaseOperatorType.INSERT)
public int insertAiKey(AiKey aiKey);
/**
*
*
* @param aiKey
* @return
*/
@AutoFill(BaseOperatorType.UPDATE)
public int updateAiKey(AiKey aiKey);
/**
*
*
* @param id
* @return
*/
public int deleteAiKeyById(Long id);
/**
*
*
* @param ids
* @return
*/
public int deleteAiKeyByIds(Long[] ids);
@Select("select `key`, host, model_list, type, status, `limit`, create_time, create_by, update_time, update_by, user_id, is_del from ai_key where is_del = 0 and user_id = #{userId}")
List<AiKey> list(Long userId);
}

@ -1,61 +0,0 @@
package com.ruoyi.system.ai.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.muta.ai.config.ChatConfig;
/**
* Mapper
*
* @author mutaai
* @date 2024-05-13
*/
public interface ChatConfigMapper extends BaseMapper<ChatConfig> {
/**
*
*
* @param id
* @return
*/
public ChatConfig selectChatConfigById(Long id);
/**
*
*
* @param chatConfig
* @return
*/
public List<ChatConfig> selectChatConfigList(ChatConfig chatConfig);
/**
*
*
* @param chatConfig
* @return
*/
public int insertChatConfig(ChatConfig chatConfig);
/**
*
*
* @param chatConfig
* @return
*/
public int updateChatConfig(ChatConfig chatConfig);
/**
*
*
* @param id
* @return
*/
public int deleteChatConfigById(Long id);
/**
*
*
* @param ids
* @return
*/
public int deleteChatConfigByIds(Long[] ids);
}

@ -1,13 +0,0 @@
package com.ruoyi.system.ai.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.muta.ai.domain.MessageFile;
import org.apache.ibatis.annotations.Mapper;
/**
* @author
* @Date: 2024/05/17/15:16
*/
@Mapper
public interface MessageFileMapper extends BaseMapper<MessageFile> {
}

@ -1,20 +0,0 @@
package com.ruoyi.system.ai.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.muta.ai.domain.MessageEntity;
import com.muta.common.core.domain.entity.SysUser;
import com.muta.system.domain.Message;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author: Larry
* @Date: 2024 /05 /20 / 13:02
* @Description:
*/
@Mapper
public interface MessageMapper extends BaseMapper<MessageEntity> {
List<MessageEntity> selectByFilter(SysUser sysUser);
}

@ -1,16 +0,0 @@
package com.ruoyi.system.ai.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.muta.ai.domain.MessageSession;
import org.apache.ibatis.annotations.Mapper;
/**
* @author
* @Date: 2024/05/13/16:09
*/
@Mapper
public interface MessageSessionMapper extends BaseMapper<MessageSession> {
}

@ -1,39 +0,0 @@
package com.ruoyi.system.ai.mq.listener;//package com.muta.ai.mq.listener;
//
//import cn.hutool.json.JSONUtil;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.muta.ai.domain.MessageEntity;
//import com.muta.ai.domain.event.MessageEvent;
//import com.muta.ai.service.IMessageService;
//import com.muta.ai.service.impl.BaseChatService;
//import com.rabbitmq.client.Channel;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.annotation.RabbitHandler;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
//import org.springframework.amqp.support.converter.MessageConverter;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//
///**
// * @author: Larry
// * @Date: 2024 /05 /15 / 17:44
// * @Description:
// */
//@Component
//
//public class MessageListener {
// @Resource
// private BaseChatService baseChatService;
// @RabbitHandler
// @RabbitListener(queues = "message.queue")
// public void listenMessage(String message, Channel channel){
// MessageEntity messageEntity = JSONUtil.toBean(message, MessageEntity.class);
// System.out.println(messageEntity.getContent());
// }
//
//}

@ -1,49 +0,0 @@
package com.ruoyi.system.ai.mq.producer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.muta.ai.domain.MessageEntity;
import com.muta.ai.domain.event.MessageEvent;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author: Larry
* @Date: 2024 /05 /16 / 20:29
* @Description:
*/
@Component
public class MessageSender {
@Value("${mqconfig.message_event_exchange}")
private String eventExchange;
/**
*
*/
@Value("${mqconfig.message_queue}")
private String MessageQueue;
/**
* key
* key
*/
@Value("${mqconfig.message_routing_key}")
private String MessageRoutingKey;
@Resource
private RabbitTemplate rabbitTemplate;
public void addSyncMessage(MessageEntity message){
rabbitTemplate.convertAndSend(eventExchange,MessageRoutingKey,message);
}
}

@ -1,563 +0,0 @@
package com.ruoyi.system.ai.service;//package com.muta.ai.service;
//
//import com.alibaba.fastjson.JSONObject;
//import com.google.gson.annotations.SerializedName;
//import com.google.gson.Gson;
//import io.reactivex.BackpressureStrategy;
//import io.reactivex.Flowable;
//import netscape.javascript.JSObject;
//
//import java.io.IOException;
//import java.util.List;
//import java.util.Objects;
//
//
//
//enum ChatMessageRole {
// SYSTEM, USER, ASSISTANT;
//
// public String value() {
// return this.name().toLowerCase();
// }
//}
//
//class ChatCompletionMessage {
// public String role;
// public String name;
// public String content;
// public Boolean partial;
//
// public ChatCompletionMessage(String role, String content) {
// this.role = role;
// this.content = content;
// }
//
// public ChatCompletionMessage(String role, String name, String content, Boolean partial) {
// this.role = role;
// this.name = name;
// this.content = content;
// this.partial = partial;
// }
//
// public String getName() {
// return name;
// }
//
// public String getContent() {
// return content;
// }
//
// public Boolean getPartial() {
// return partial;
// }
//}
//
//class ChatCompletionStreamChoiceDelta {
// private String content;
// private String role;
//
// public String getContent() {
// return content;
// }
//
// public String getRole() {
// return role;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public void setRole(String role) {
// this.role = role;
// }
//
// public ChatCompletionStreamChoiceDelta(String content, String role) {
// this.content = content;
// this.role = role;
// }
//}
//
//class Usage {
// private int promptTokens;
// private int completionTokens;
// private int totalTokens;
//
// public int getPromptTokens() {
// return promptTokens;
// }
//
// public int getCompletionTokens() {
// return completionTokens;
// }
//
// public int getTotalTokens() {
// return totalTokens;
// }
//}
//
//class ChatCompletionStreamChoice {
// private int index;
// private ChatCompletionStreamChoiceDelta delta;
//
// @SerializedName("finish_reason")
// private String finishReason;
// private Usage usage;
//
// public int getIndex() {
// return index;
// }
//
// public ChatCompletionStreamChoiceDelta getDelta() {
// return delta;
// }
//
// public String getFinishReason() {
// return finishReason;
// }
//
// public Usage getUsage() {
// return usage;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public void setDelta(ChatCompletionStreamChoiceDelta delta) {
// this.delta = delta;
// }
//
// public void setFinishReason(String finishReason) {
// this.finishReason = finishReason;
// }
//
// public void setUsage(Usage usage) {
// this.usage = usage;
// }
//
// public ChatCompletionStreamChoice(int index, ChatCompletionStreamChoiceDelta delta, String finishReason, Usage usage) {
// this.index = index;
// this.delta = delta;
// this.finishReason = finishReason;
// this.usage = usage;
// }
//}
//
//class ChatCompletionStreamResponse {
// private String id;
// private String object;
// private long created;
// private String model;
// private List<ChatCompletionStreamChoice> choices;
//
// public String getId() {
// return id;
// }
//
// public String getObject() {
// return object;
// }
//
// public long getCreated() {
// return created;
// }
//
// public String getModel() {
// return model;
// }
//
// public List<ChatCompletionStreamChoice> getChoices() {
// return choices;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public void setObject(String object) {
// this.object = object;
// }
//
// public void setCreated(long created) {
// this.created = created;
// }
//}
//
//class ChatCompletionChoice {
// private int index;
// private ChatCompletionMessage message;
//
// @SerializedName("finish_reason")
// private String finishReason;
//
// public int getIndex() {
// return index;
// }
//
// public ChatCompletionMessage getMessage() {
// return message;
// }
//
// public String getFinishReason() {
// return finishReason;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public void setMessage(ChatCompletionMessage message) {
// this.message = message;
// }
//
// public void setFinishReason(String finishReason) {
// this.finishReason = finishReason;
// }
//
//}
//
//class ChatCompletionResponse {
// private String id;
// private String object;
// private long created;
// private String model;
// private List<ChatCompletionChoice> choices;
// private Usage usage;
//
// public String getId() {
// return id;
// }
//
// public String getObject() {
// return object;
// }
//
// public long getCreated() {
// return created;
// }
//
// public String getModel() {
// return model;
// }
//
// public List<ChatCompletionChoice> getChoices() {
// if (choices == null) {
// return List.of();
// }
// return choices;
// }
//}
//
//
//class ChatCompletionRequest {
// public String model;
// public List<ChatCompletionMessage> messages;
//
// @SerializedName("max_tokens")
// public int maxTokens;
//
// @SerializedName("temperature")
// public float temperature;
// public float topP;
//
// public Integer n;
// public boolean stream;
// public List<String> stop;
//
// @SerializedName("presence_penalty")
// public float presencePenalty;
//
// @SerializedName("frequency_penalty")
// public float frequencyPenalty;
//
// public String user;
//
// public List<ChatCompletionMessage> getMessages() {
// return messages;
// }
//
// public ChatCompletionRequest(String model, List<ChatCompletionMessage> messages, int maxTokens, float temperature, int n) {
// this.model = model;
// this.messages = messages;
// this.maxTokens = maxTokens;
// this.temperature = temperature;
// this.n = n;
// }
//
//}
//
//class Model {
// private String id;
// private String object;
//
// @SerializedName("owner_by")
// private String ownedBy;
// private String root;
// private String parent;
//
// public String getId() {
// return id;
// }
//
// public String getObject() {
// return object;
// }
//
// public String getOwnedBy() {
// return ownedBy;
// }
//
// public String getRoot() {
// return root;
// }
//
// public String getParent() {
// return parent;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public void setObject(String object) {
// this.object = object;
// }
//
// public void setOwnedBy(String ownedBy) {
// this.ownedBy = ownedBy;
// }
//
// public void setRoot(String root) {
// this.root = root;
// }
//
// public void setParent(String parent) {
// this.parent = parent;
// }
//
// public Model(String id, String object, String ownedBy, String root, String parent) {
// this.id = id;
// this.object = object;
// this.ownedBy = ownedBy;
// this.root = root;
// this.parent = parent;
// }
//}
//
//class ModelsList {
// private List<Model> data;
//
// public List<Model> getData() {
// return data;
// }
//
// public void setData(List<Model> data) {
// this.data = data;
// }
//
// public ModelsList(List<Model> data) {
// this.data = data;
// }
//}
//
//class Client {
// private static final String DEFAULT_BASE_URL = "https://api.moonshot.cn/v1";
//
// private static final String CHAT_COMPLETION_SUFFIX = "/chat/completions";
// private static final String MODELS_SUFFIX = "/models";
// private static final String FILES_SUFFIX = "/files";
//
// private String baseUrl;
// private String apiKey;
//
// public Client(String apiKey) {
// this(apiKey, DEFAULT_BASE_URL);
// }
//
// public Client(String apiKey, String baseUrl) {
// this.apiKey = apiKey;
// if (baseUrl.endsWith("/")) {
// baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
// }
// this.baseUrl = baseUrl;
// }
//
// public String getChatCompletionUrl() {
// return baseUrl + CHAT_COMPLETION_SUFFIX;
// }
//
// public String getModelsUrl() {
// return baseUrl + MODELS_SUFFIX;
// }
//
// public String getFilesUrl() {
// return baseUrl + FILES_SUFFIX;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public ModelsList ListModels() throws IOException {
// okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
// okhttp3.Request request = new okhttp3.Request.Builder()
// .url(getModelsUrl())
// .addHeader("Authorization", "Bearer " + getApiKey())
// .build();
// try {
// okhttp3.Response response = client.newCall(request).execute();
// String body = response.body().string();
// Gson gson = new Gson();
// return gson.fromJson(body, ModelsList.class);
// } catch (java.io.IOException e) {
// e.printStackTrace();
// throw e;
// }
// }
//
//
// public ChatCompletionResponse ChatCompletion(ChatCompletionRequest request) throws IOException {
// request.stream = false;
// okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
// okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
// okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, new Gson().toJson(request));
// okhttp3.Request httpRequest = new okhttp3.Request.Builder()
// .url(getChatCompletionUrl())
// .addHeader("Authorization", "Bearer " + getApiKey())
// .addHeader("Content-Type", "application/json")
// .post(body)
// .build();
// try {
// okhttp3.Response response = client.newCall(httpRequest).execute();
// String responseBody = response.body().string();
// System.out.println(responseBody);
// Gson gson = new Gson();
// return gson.fromJson(responseBody, ChatCompletionResponse.class);
// } catch (java.io.IOException e) {
// e.printStackTrace();
// throw e;
// }
// }
//
// // return a stream of ChatCompletionStreamResponse
// public Flowable<ChatCompletionStreamResponse> ChatCompletionStream(ChatCompletionRequest request) throws IOException {
// request.stream = true;
// okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
// okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
// okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, new Gson().toJson(request));
// okhttp3.Request httpRequest = new okhttp3.Request.Builder()
// .url(getChatCompletionUrl())
// .addHeader("Authorization", "Bearer " + getApiKey())
// .addHeader("Content-Type", "application/json")
// .post(body)
// .build();
// okhttp3.Response response = client.newCall(httpRequest).execute();
// if (response.code() != 200) {
// throw new RuntimeException("Failed to start stream: " + response.body().string());
// }
//
// // get response body line by line
// return Flowable.create(emitter -> {
// okhttp3.ResponseBody responseBody = response.body();
// if (responseBody == null) {
// emitter.onError(new RuntimeException("Response body is null"));
// return;
// }
// String line;
// while ((line = responseBody.source().readUtf8Line()) != null) {
// if (line.startsWith("data:")) {
// line = line.substring(5);
// line = line.trim();
// }
// if (Objects.equals(line, "[DONE]")) {
// emitter.onComplete();
// return;
// }
// line = line.trim();
// if (line.isEmpty()) {
// continue;
// }
// Gson gson = new Gson();
// JSONObject json = gson.fromJson(line, JSONObject.class);
// json.getJSONArray("choices").getJSONObject(0).getJSONObject("finish_reason");
// ChatCompletionStreamResponse streamResponse = gson.fromJson(line, ChatCompletionStreamResponse.class);
// emitter.onNext(streamResponse);
// }
// emitter.onComplete();
// }, BackpressureStrategy.BUFFER);
// }
//}
//
//public class rld {
// public static void main(String... args) {
// String apiKey = System.getenv("MOONSHOT_API_KEY");
// if (apiKey == null) {
// System.out.println("Please set MOONSHOT_API_KEY env");
// return;
// }
// Client client = new Client(apiKey);
// try {
// ModelsList models = client.ListModels();
// for (Model model : models.getData()) {
// System.out.println(model.getId());
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// final List<ChatCompletionMessage> messages = List.of(
// new ChatCompletionMessage(ChatMessageRole.SYSTEM.value(),
// "你是 Kimi由 Moonshot AI 提供的人工智能助手你更擅长中文和英文的对话。你会为用户提供安全有帮助准确的回答。同时你会拒绝一些涉及恐怖主义种族歧视黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。"),
// new ChatCompletionMessage(ChatMessageRole.USER.value(),
// "你好我叫李雷1+1等于多少")
// );
//
//// try {
//// ChatCompletionResponse response = client.ChatCompletion(new ChatCompletionRequest(
//// "moonshot-v1-8k",
//// messages,
//// 50,
//// 0.3f,
//// 1
//// ));
//// for (ChatCompletionChoice choice : response.getChoices()) {
//// System.out.println(choice.getMessage().getContent());
//// }
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
//AtomicR
// try {
// client.ChatCompletionStream(new ChatCompletionRequest(
// "moonshot-v1-8k",
// messages,
// 50,
// 0.3f,
// 1
// )).subscribe(
// streamResponse -> {
// if (streamResponse.getChoices().isEmpty()) {
// return;
// }
// for (ChatCompletionStreamChoice choice : streamResponse.getChoices()) {
// String finishReason = choice.getFinishReason();
// if (finishReason != null) {
// System.out.println("finish reason: " + finishReason);
// continue;
// }
// System.out.println(choice.getDelta().getContent());
// }
// },
// error -> {
// error.printStackTrace();
// },
// () -> {
// System.out.println("complete");
// }
// );
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//}

@ -1,87 +0,0 @@
package com.ruoyi.system.ai.service;
import java.util.List;
import com.muta.ai.domain.AiKey;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* Service
*
* @author mutaai
* @date 2024-05-16
*/
public interface IAiKeyService extends IService<AiKey> {
/**
*
*
* @param id
* @return
*/
public AiKey selectAiKeyById(Long id);
/**
*
*
* @return
*/
public List<AiKey> selectAiKeyList();
/**
*
*
* @param aiKey
* @return
*/
public int insertAiKey(AiKey aiKey);
/**
*
*
* @param aiKey
* @return
*/
public int updateAiKey(AiKey aiKey);
/**
*
*
* @param ids
* @return
*/
public int deleteAiKeyByIds(Long[] ids);
/**
*
*
* @param id
* @return
*/
public int deleteAiKeyById(Long id);
/**
*
*
* @param key
* @return
*/
public String getLimitByKey(String key);
/**
* key
* @param key
* @return
*/
public Integer isAvailable(String key);
/**
* idAiKey(String)
* @param
* @return
*/
List<AiKey> getAiKeyStrById(Long userId);
/**
* Key
*/
void updateKeyLimit();
}

@ -1,49 +0,0 @@
package com.ruoyi.system.ai.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.muta.ai.config.ChatConfig;
import java.util.List;
/**
* Service
*
* @author mutaai
* @date 2024-05-13
*/
public interface IChatConfigService extends IService<ChatConfig> {
/**
*
*
* @param id
* @return
*/
public ChatConfig selectChatConfigById(Long id);
/**
*
*
* @param chatConfig
* @return
*/
public List<ChatConfig> selectChatConfigList(ChatConfig chatConfig);
/**
*
*
* @param chatConfig
* @return
*/
public int insertChatConfig(ChatConfig chatConfig);
/**
*
*
* @param chatConfig
* @return
*/
public int updateChatConfig(ChatConfig chatConfig);
}

@ -1,20 +0,0 @@
package com.ruoyi.system.ai.service;
import com.muta.ai.domain.ChatCompletionMessage;
import com.muta.ai.chain.MusicProcessAggregate;
import com.muta.ai.chain.UserAccountQuotaEntity;
import java.util.List;
/**
* @author: Larry
* @Date: 2024 /05 /09 / 20:06
* @Description:
*/
public interface IChatService {
MusicProcessAggregate initChatData(Long userId, String model, List<ChatCompletionMessage> messages);
UserAccountQuotaEntity initUserData(Long userId);
}

@ -1,13 +0,0 @@
package com.ruoyi.system.ai.service;
import org.springframework.web.multipart.MultipartFile;
/**
* @author: Larry
* @Date: 2024 /05 /15 / 20:59
* @Description:
*/
public interface IChatUploadService {
String upload(MultipartFile file);
String analyzeFile(String path);
}

@ -1,16 +0,0 @@
package com.ruoyi.system.ai.service;
import com.muta.ai.chain.MusicProcessAggregate;
import com.muta.ai.domain.RuleLogicEntity;
/**
* @author Fuzhengwei bugstack.cn @
* @description
* @create 2023-09-16 16:59
*/
public interface ILogicFilter<T> {
RuleLogicEntity<MusicProcessAggregate> filter(MusicProcessAggregate chatProcess, T data) throws Exception;
}

@ -1,16 +0,0 @@
package com.ruoyi.system.ai.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.muta.ai.domain.MessageFile;
import org.springframework.web.multipart.MultipartFile;
/**
* @author
* @Date: 2024/05/17/15:15
*/
public interface IMessageFileService extends IService<MessageFile> {
MessageFile upload(MultipartFile file) throws Exception;
//根据url获取文件解析信息
String getContentByUrl(String url);
}

@ -1,19 +0,0 @@
package com.ruoyi.system.ai.service;
import com.muta.ai.domain.MessageEntity;
import com.muta.common.core.domain.entity.SysUser;
import com.muta.system.domain.Message;
import java.util.List;
/**
* @author: Larry
* @Date: 2024 /05 /20 / 13:01
* @Description:
*/
public interface IMessageService {
//根据权限返回对应消息列表
List<MessageEntity> getList(SysUser sysUser);
void add(MessageEntity message);
}

@ -1,11 +0,0 @@
package com.ruoyi.system.ai.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.muta.ai.domain.MessageSession;
/**
* @author
* @Date: 2024/05/13/16:07
*/
public interface IMessageSessionService extends IService<MessageSession> {
}

@ -1,7 +0,0 @@
package com.ruoyi.system.ai.service;
import java.util.List;
public interface IModelService {
List<String> getModelList();
}

@ -1,163 +0,0 @@
package com.ruoyi.system.ai.service.impl;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muta.ai.mapper.AiKeyMapper;
import com.muta.ai.util.MoonshotAiUtils;
import com.muta.common.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.muta.ai.domain.AiKey;
import com.muta.ai.service.IAiKeyService;
import org.web3j.crypto.MnemonicUtils;
import java.math.BigDecimal;
import java.security.Security;
import java.util.List;
/**
* Service
*
* @author mutaai
* @date 2024-05-16
*/
@Service
public class AiKeyServiceImpl extends ServiceImpl<AiKeyMapper, AiKey> implements IAiKeyService {
@Autowired
private AiKeyMapper aiKeyMapper;
/**
*
*
* @param id
* @return
*/
@Override
public AiKey selectAiKeyById(Long id) {
return aiKeyMapper.selectAiKeyById(id);
}
/**
*
*
* @return
*/
@Override
public List<AiKey> selectAiKeyList() {
return aiKeyMapper.selectAiKeyList();
}
/**
*
*
* @param aiKey
* @return
*/
@Override
public int insertAiKey(AiKey aiKey) {
String limit = getLimitByKey(aiKey.getKey());
aiKey.setLimit(new BigDecimal(limit));
aiKey.setUserId(SecurityUtils.getUserId());
return aiKeyMapper.insertAiKey(aiKey);
}
/**
*
*
* @param aiKey
* @return
*/
@Override
public int updateAiKey(AiKey aiKey) {
return aiKeyMapper.updateAiKey(aiKey);
}
/**
*
*
* @param ids
* @return
*/
@Override
public int deleteAiKeyByIds(Long[] ids) {
return aiKeyMapper.deleteAiKeyByIds(ids);
}
/**
*
*
* @param id
* @return
*/
@Override
public int deleteAiKeyById(Long id) {
return aiKeyMapper.deleteAiKeyById(id);
}
/**
*
*
* @param key
* @return
*/
@Override
public String getLimitByKey(String key) {
String balance = MoonshotAiUtils.getBalanceByKey(key);
Object availableBalance = JSON.parseObject(balance)
.getJSONObject("data")
.get("available_balance");
return availableBalance.toString();
}
/**
* key
* @param key
* @return
*/
@Override
public Integer isAvailable(String key) {
if (ObjectUtils.isEmpty(key)) return 1;
// 0可用 1不可用
String response = MoonshotAiUtils.getBalanceByKey(key);
Object error = JSON.parseObject(response).get("error");
if (ObjectUtils.isEmpty(error)) {
return 0;
} else {
return 1;
}
}
/**
* user_idAiKey
* @param
* @return
*/
@Override
public List<AiKey> getAiKeyStrById(Long userId) {
System.out.println(userId);
return aiKeyMapper.list(userId);
}
/**
* Key
*
* IDKeyKey
*/
@Override
public void updateKeyLimit() {
// 获取当前登录用户的ID
Long userId = SecurityUtils.getUserId();
// 构造查询条件查询当前用户所有的Key
QueryWrapper<AiKey> wrapper = new QueryWrapper<AiKey>().eq("user_id", userId);
List<AiKey> aiKeyList = aiKeyMapper.selectList(wrapper);
// 遍历查询结果更新每个Key的额度
aiKeyList.forEach(key -> {
key.setLimit(new BigDecimal(getLimitByKey(key.getKey())));
});
}
}

@ -1,75 +0,0 @@
package com.ruoyi.system.ai.service.impl;//package com.muta.ai.service.impl;
//
//import com.muta.ai.chain.MusicProcessAggregate;
//import com.muta.ai.domain.MessageEntity;
//import com.muta.ai.domain.RuleLogicEntity;
//import com.muta.ai.chain.UserAccountQuotaEntity;
//import com.muta.ai.enums.LogicCheckEnum;
//import com.muta.ai.factory.DefaultLogicFactory;
//import com.muta.ai.service.ILogicFilter;
//import com.muta.ai.service.IMessageService;
//import com.muta.common.constant.Constants;
//import com.muta.common.core.domain.entity.UserExtra;
//import com.muta.common.utils.SecurityUtils;
//import com.muta.log.domain.IntegralLog;
//import com.muta.log.service.impl.MessageIntegralLogServiceImpl;
//import com.muta.system.mapper.UserExtraMapper;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.annotation.Resource;
//import java.util.Map;
//
///**
// * @author: Larry
// * @Date: 2024 /05 /09 / 16:05
// * @Description: 前置过滤规则处理
// */
//public class BaseChatService {
// @Resource
// private DefaultLogicFactory logicFactory;
// //后面可拓展为根据需要传入对应过滤器执行
// @Resource
// private UserExtraMapper userExtraMapper;
// @Resource
// private IMessageService messageService;
// @Resource
// private MessageIntegralLogServiceImpl messageIntegralLogService;
// //前置过滤
// protected RuleLogicEntity<MusicProcessAggregate> doCheckLogic(MusicProcessAggregate chatProcess, UserAccountQuotaEntity userAccountQuotaEntity) throws Exception {
// //获得所有的拦截器
// Map<String, ILogicFilter<UserAccountQuotaEntity>> logicFilterMap = logicFactory.openLogicFilter();
// //定义返回结果
// RuleLogicEntity<MusicProcessAggregate> entity = null;
// //遍历所有拦截器,如果拦截则结束并返回,否则放行
// for (ILogicFilter<UserAccountQuotaEntity> filter : logicFilterMap.values()) {
// entity = filter.filter(chatProcess,userAccountQuotaEntity);
// if(entity.getType().equals(LogicCheckEnum.REFUSE)){
// return entity;
// }
// }
// //全部方向后通过
// return entity != null ? entity : RuleLogicEntity.<MusicProcessAggregate>builder()
// .type(LogicCheckEnum.SUCCESS).data(chatProcess).build();
//
// }
// //后置过滤
// @Transactional
// public void PostRule(MusicProcessAggregate chatProcess, UserAccountQuotaEntity userAccountQuotaEntity, MessageEntity message){
// double result = chatProcess.getTokenNum() / (double) chatProcess.getModelConsumer();
// Integer consumption = Math.toIntExact(Math.round(result));
// //扣减积分
// increaseIntegral(consumption,userAccountQuotaEntity.getUserId());
// //新增积分记录
// IntegralLog integralLog = IntegralLog.builder()
// .value(consumption+"积分")
// .build();
// messageIntegralLogService.insertLog(integralLog);
// //新增消息记录
//// messageService.add(message);
// }
// private void increaseIntegral(Integer integral,Long userId){
// userExtraMapper.IncreaseIntegralByUserId(integral,userId);
// }
//
//
//}

@ -1,83 +0,0 @@
package com.ruoyi.system.ai.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import com.muta.ai.config.ChatConfig;
import com.muta.ai.mapper.ChatConfigMapper;
import com.muta.ai.service.IChatConfigService;
import com.muta.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Service
*
* @author mutaai
* @date 2024-05-13
*/
@Service
public class ChatConfigServiceImpl extends ServiceImpl<ChatConfigMapper, ChatConfig> implements IChatConfigService {
@Resource
private ChatConfigMapper chatConfigMapper;
/**
*
*
* @param
* @return
*/
@Override
public ChatConfig selectChatConfigById(Long userId) {
LambdaQueryWrapper<ChatConfig> chatConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
chatConfigLambdaQueryWrapper.eq(userId!=null,ChatConfig::getUserId, userId);
return chatConfigMapper.selectOne(chatConfigLambdaQueryWrapper);
}
/**
*
*
* @param chatConfig
* @return
*/
@Override
public List<ChatConfig> selectChatConfigList(ChatConfig chatConfig) {
return chatConfigMapper.selectChatConfigList(chatConfig);
}
/**
*
*
* @param chatConfig
* @return
*/
@Override
public int insertChatConfig(ChatConfig chatConfig) {
return chatConfigMapper.insert(chatConfig);
}
/**
*
*
* @param chatConfig
* @return
*/
@Override
public int updateChatConfig(ChatConfig chatConfig) {
System.out.println(chatConfig.getUserId());
LambdaQueryWrapper<ChatConfig> chatConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
chatConfigLambdaQueryWrapper.eq(SecurityUtils.getUserId()!=null,ChatConfig::getUserId, SecurityUtils.getUserId());
return chatConfigMapper.update(chatConfig,chatConfigLambdaQueryWrapper);
}
/**
*
*
* @param ids
* @return
*/
}

@ -1,110 +0,0 @@
package com.ruoyi.system.ai.service.impl;//package com.muta.ai.service.impl;
//
//import com.alibaba.fastjson2.JSON;
//import com.alibaba.fastjson2.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.muta.ai.config.ChatConfig;
//
//import com.muta.ai.domain.*;
//import com.muta.ai.domain.dto.MessageHistoryKimi;
//import com.muta.ai.service.IAiKeyService;
//import com.muta.ai.service.IChatConfigService;
//import com.muta.ai.service.IChatService;
//import com.muta.ai.util.MoonshotAiUtils;
//import com.muta.common.core.domain.entity.UserExtra;
//import com.muta.system.mapper.UserExtraMapper;
//import com.muta.system.service.ICommonSettingService;
//import com.muta.system.service.impl.CommonSettingServiceImpl;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.math.BigDecimal;
//import java.util.Comparator;
//import java.util.List;
//import java.util.Optional;
//import java.util.stream.Collectors;
//
///**
// * @author: Larry
// * @Date: 2024 /05 /09 / 18:06
// * @Description:
// */
//@SuppressWarnings("all")
//@Service
//public class KimiChatService extends BaseChatService implements IChatService {
// @Resource
// private IAiKeyService aiKeyService;
// @Resource
// private UserExtraMapper userExtraMapper;
// @Resource
// private IChatConfigService chatConfigService;
// @Resource
// private ICommonSettingService commonSettingService;
//
// @Override
// public UserAccountQuotaEntity initUserData(Long userId) {
// LambdaQueryWrapper<UserExtra> userExtraLambdaQueryWrapper = new LambdaQueryWrapper<>();
// userExtraLambdaQueryWrapper.eq(userId!=null,UserExtra::getUserId,userId);
// UserExtra userExtra = userExtraMapper.selectOne(userExtraLambdaQueryWrapper);
// ChatConfig config = chatConfigService.selectChatConfigById(userId);
// return UserAccountQuotaEntity.builder()
// .userId(userId)
// .integral(userExtra.getIntegral())
// .maxToken(config.getMaxToken())
// .build();
// }
//
// @Override
// public MusicProcessAggregate initChatData(Long userId, String model, List<ChatCompletionMessage> messages) {
// String key = LoadBalancingKey(userId);
// Integer tokenNum = getTokenNum(model, messages);
// return MusicProcessAggregate.builder()
// .messages(messages)
// .model(model)
// .userId(userId)
// .key(key)
// .tokenNum(tokenNum)
// .modelConsumer(commonSettingService.getRatioByName(model))
// .build();
// }
//
// private Integer getTokenNum(String model, List<ChatCompletionMessage> messages) {
// List<MessageHistoryKimi> messageHistoryKimis = messages.stream().map(
// chatCompletionMessage -> MessageHistoryKimi.builder()
// .role(chatCompletionMessage.getRole())
// .content(chatCompletionMessage.getContent())
// .build()
//).collect(Collectors.toList());
// // 调用工具类方法,估算对话的令牌数量
// String response = MoonshotAiUtils.estimateTokenCount(model, messageHistoryKimis);
// JSONObject jsonObject = JSON.parseObject(response);
// return jsonObject.getJSONObject("data").getInteger("total_tokens");
// }
//
// @Override
// public RuleLogicEntity<MusicProcessAggregate> doCheckLogic(MusicProcessAggregate chatProcess, UserAccountQuotaEntity userAccountQuotaEntity) throws Exception {
// return super.doCheckLogic(chatProcess, userAccountQuotaEntity);
// }
//
// @Override
// public void PostRule(MusicProcessAggregate chatProcess, UserAccountQuotaEntity userAccountQuotaEntity, MessageEntity message) {
// super.PostRule(chatProcess, userAccountQuotaEntity, message);
// }
//
// private String LoadBalancingKey(Long userId) {
// //找到该用户的最近代理
// LambdaQueryWrapper<UserExtra> userExtraMapperLambdaQueryWrapper = new LambdaQueryWrapper<>();
// userExtraMapperLambdaQueryWrapper.eq(userId != null, UserExtra::getUserId, userId);
// UserExtra extraInfo = userExtraMapper.selectOne(userExtraMapperLambdaQueryWrapper);
// List<AiKey> aiKeyList = aiKeyService.getAiKeyStrById(extraInfo.getLowestId());
// //找到下面额度最大的key实现负载均衡
// if (aiKeyList != null && !aiKeyList.isEmpty()) {
// AiKey max = aiKeyList.stream()
// .filter(aiKey -> aiKey.getKey() != null)
// .max(Comparator.comparing(AiKey::getLimit))
// .orElse(null);
// return max.getKey();
// }
// return null;
// }
//}

@ -1,117 +0,0 @@
package com.ruoyi.system.ai.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muta.ai.domain.MessageFile;
import com.muta.ai.mapper.MessageFileMapper;
import com.muta.ai.service.IMessageFileService;
import com.muta.ai.util.DocumentReaderUtils;
import com.muta.common.core.service.ISysFileService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* @author
* @Date: 2024/05/17/15:15
*/
@Service
public class MessageFileServiceImpl extends ServiceImpl<MessageFileMapper, MessageFile> implements IMessageFileService {
@Resource
private MessageFileMapper messageFileMapper;
@Resource
private ISysFileService aliOssServiceImpl;
@Resource
@Qualifier("asyncPoolTaskExecutor")
ThreadPoolTaskExecutor executor;
@Override
public MessageFile upload(MultipartFile file) throws Exception {
MessageFile messageFile = new MessageFile();
messageFile.setUrl(aliOssServiceImpl.uploadFile(file));
File tempFile = multipartFile2File(file);
messageFile.setAnalysisContent(DocumentReaderUtils.readDocument(tempFile));
if (tempFile.exists()) {
tempFile.delete();
}
messageFile.setName(file.getOriginalFilename());
messageFile.setSize(formatFileSize(file.getSize()));
messageFileMapper.insert(messageFile);
return messageFile;
}
@Override
public String getContentByUrl(String url) {
LambdaQueryWrapper<MessageFile> lqw = new LambdaQueryWrapper<>();
lqw.eq(MessageFile::getUrl, url);
MessageFile messageFile = messageFileMapper.selectOne(lqw);
return messageFile.getAnalysisContent();
}
private CompletableFuture<MessageFile> futureUpload(MultipartFile file){
return CompletableFuture.supplyAsync(() -> {
try {
MessageFile messageFile = new MessageFile();
messageFile.setUrl(aliOssServiceImpl.uploadFile(file));
File tempFile = multipartFile2File(file);
messageFile.setAnalysisContent(DocumentReaderUtils.readDocument(tempFile));
deleteTempFile(tempFile);
messageFile.setName(file.getOriginalFilename());
messageFile.setSize(formatFileSize(file.getSize()));
messageFileMapper.insert(messageFile);
return messageFile;
} catch (Exception e) {
// 根据需要处理异常,或者重新抛出
throw new RuntimeException(e);
}
}, executor); // 使用提供的线程池执行上传任务
}
private void deleteTempFile(File tempFile) throws IOException {
if (tempFile.exists()) {
boolean delete = tempFile.delete();
if (!delete) {
throw new IOException("Failed to delete temporary file: " + tempFile.getAbsolutePath());
}
}
}
public File multipartFile2File (MultipartFile multipartFile) throws IOException {
// 获取原始文件名
String originalFilename = multipartFile.getOriginalFilename();
// 获取文件扩展名
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
// 创建临时文件
File file = File.createTempFile("temp-" + UUID.randomUUID(), fileExtension);
System.err.println(file);
// 将MultipartFile对象的内容写入临时文件
multipartFile.transferTo(file);
return file;
}
public String formatFileSize(long bytes) {
double kilobytes = bytes / 1024.0;
double megabytes = kilobytes / 1024.0;
if (megabytes >= 1) {
return String.format("%.2f MB", megabytes);
} else {
return String.format("%.2f KB", kilobytes);
}
}
}

@ -1,31 +0,0 @@
package com.ruoyi.system.ai.service.impl;
import com.muta.ai.domain.MessageEntity;
import com.muta.ai.mapper.MessageMapper;
import com.muta.ai.service.IMessageService;
import com.muta.common.core.domain.entity.SysUser;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: Larry
* @Date: 2024 /05 /20 / 13:01
* @Description:
*/
@Service
public class MessageServiceImpl implements IMessageService {
@Resource
private MessageMapper messageMapper;
@Override
public void add(MessageEntity message) {
messageMapper.insert(message);
}
@Override
public List<MessageEntity> getList(SysUser sysUser) {
return messageMapper.selectByFilter(sysUser);
}
}

@ -1,15 +0,0 @@
package com.ruoyi.system.ai.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muta.ai.domain.MessageSession;
import com.muta.ai.mapper.MessageSessionMapper;
import com.muta.ai.service.IMessageSessionService;
import org.springframework.stereotype.Service;
/**
* @author
* @Date: 2024/05/13/16:07
*/
@Service
public class MessageSessionServiceImpl extends ServiceImpl<MessageSessionMapper, MessageSession> implements IMessageSessionService {
}

@ -1,36 +0,0 @@
package com.ruoyi.system.ai.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.muta.ai.service.IModelService;
import com.muta.ai.util.MoonshotAiUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class ModelService implements IModelService {
/**
* MoonshotAiUtilsJSONID
* @return ID
*/
@Override
public List<String> getModelList() {
List<String> models = new ArrayList<>();
// 获取模型列表的JSON字符串
String modelListJSON = MoonshotAiUtils.getModelList();
// 解析JSON字符串获取模型数据数组
JSONArray data = JSON.parseObject(modelListJSON).getJSONArray("data");
// 遍历数据数组提取模型ID并添加到列表中
data.forEach(item -> {
JSONObject model = (JSONObject) item;
models.add(model.getString("id"));
});
return models;
}
}

@ -1,52 +0,0 @@
package com.ruoyi.system.ai.service.impl;//package com.muta.ai.service.impl;
//
//import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
//import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
//import com.muta.ai.annotation.LogicStrategy;
//import com.muta.ai.domain.*;
//import com.muta.ai.enums.LogicCheckEnum;
//import com.muta.ai.factory.DefaultLogicFactory;
//import com.muta.ai.service.ILogicFilter;
//import com.muta.common.annotation.Log;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//import java.util.List;
//
///**
// * @author Larry
// * @description 敏感词过滤
// * @create 2024-05-10 17:39
// */
//@Slf4j
//@Component
//@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.SENSITIVE_WORD)
//public class SensitiveWordFilter implements ILogicFilter<UserAccountQuotaEntity> {
// @Resource
// @Qualifier("sensitiveWordBsBean")
// SensitiveWordBs sensitiveWordBs;
// @Override
// public RuleLogicEntity<MusicProcessAggregate> filter(MusicProcessAggregate chatProcess, UserAccountQuotaEntity data) throws Exception {
// //只对当前的信息进行敏感词过滤
// ChatCompletionMessage nowMessage = chatProcess.getMessages().get(chatProcess.getMessages().size() -1);
// System.out.println();
// //调用外部依赖进行敏感词查找
// if (sensitiveWordBs.contains(nowMessage.getContent())) {
// //如果有敏感词,返回相关结果
// return RuleLogicEntity.<MusicProcessAggregate>builder()
// .type(LogicCheckEnum.REFUSE)
// .info("您的对话含有敏感词,请注意!")
// .data(chatProcess).build();
// }
//
// return RuleLogicEntity.<MusicProcessAggregate>builder()
// .type(LogicCheckEnum.SUCCESS).data(chatProcess).build();
// }
//
// public static void main(String[] args) {
//
//
// }
//}

@ -1,62 +0,0 @@
package com.ruoyi.system.ai.service.impl;//package com.muta.ai.service.impl;
//
//import com.alibaba.fastjson2.JSON;
//import com.alibaba.fastjson2.JSONObject;
//import com.muta.ai.annotation.LogicStrategy;
//import com.muta.ai.domain.*;
//import com.muta.ai.domain.dto.MessageHistoryKimi;
//import com.muta.ai.enums.LogicCheckEnum;
//import com.muta.ai.factory.DefaultLogicFactory;
//import com.muta.ai.service.ILogicFilter;
//import com.muta.ai.util.MoonshotAiUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.stream.Collectors;
//
///**
// * 该类实现了ILogicFilter接口用于过滤total_tokens。
// * 通过评估对话中消息的令牌数量,决定是否继续处理或拒绝该对话。
// */
//@Slf4j
//@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.MAX_TOKEN)
//@Component
//public class TokenFilter implements ILogicFilter<UserAccountQuotaEntity> {
//
// /**
// * 过滤方法检查对话的total_tokens数量是否超过限制。
// * @param chatProcess
// * @param data
// * @return 如果超过限制,返回拒绝信息;否则返回成功。
// * @throws Exception 如果过程中发生错误,抛出异常。
// */
//// List<MessageHistoryKimi> messageHistoryKimis = chatProcess.getMessages().stream().map(
//// chatCompletionMessage -> MessageHistoryKimi.builder()
//// .role(chatCompletionMessage.getRole())
//// .content(chatCompletionMessage.getContent())
//// .build()
//// ).collect(Collectors.toList());
//// // 调用工具类方法,估算对话的令牌数量
//// String response = MoonshotAiUtils.estimateTokenCount(chatProcess.getModel(), messageHistoryKimis);
//// JSONObject jsonObject = JSON.parseObject(response);
//// Integer total_tokens = jsonObject.getJSONObject("data").getInteger("total_tokens");
// @Override
// public RuleLogicEntity<MusicProcessAggregate> filter(MusicProcessAggregate chatProcess, UserAccountQuotaEntity data) throws Exception {
// // 检查数量是否超过配置的最大值
// if (chatProcess.getTokenNum() > data.getMaxToken()) {
// // 如果超过最大值,返回拒绝信息
// return RuleLogicEntity.<MusicProcessAggregate>builder()
// .type(LogicCheckEnum.REFUSE)
// .info("您的对话所含token数超过限制!")
// .data(chatProcess).build();
// }
//
// // 如果未超过最大值,返回成功
// return RuleLogicEntity.<MusicProcessAggregate>builder()
// .type(LogicCheckEnum.SUCCESS)
// .data(chatProcess).build();
// }
//}
//

@ -1,46 +0,0 @@
package com.ruoyi.system.ai.service.impl;//package com.muta.ai.service.impl;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.muta.ai.annotation.LogicStrategy;
//import com.muta.ai.chain.MusicProcessAggregate;
//import com.muta.ai.domain.RuleLogicEntity;
//import com.muta.ai.chain.UserAccountQuotaEntity;
//import com.muta.ai.enums.LogicCheckEnum;
//import com.muta.ai.factory.DefaultLogicFactory;
//import com.muta.ai.service.ILogicFilter;
//import com.muta.common.core.domain.entity.UserExtra;
//import com.muta.system.mapper.UserExtraMapper;
//import com.muta.system.service.ICommonSettingService;
//import com.muta.system.service.impl.CommonSettingServiceImpl;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//
///**
// * @author Fuzhengwei bugstack.cn @小傅哥
// * @description 用户额度扣减规则过滤
// * @create 2023-10-03 16:48
// */
//@Slf4j
//@Component
//@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.USER_QUOTA)
//public class UserQuotaFilter implements ILogicFilter<UserAccountQuotaEntity> {
// //调用基础业务查询积分
// @Resource
// private UserExtraMapper userExtraMapper;
// @Override
// public RuleLogicEntity<MusicProcessAggregate> filter(MusicProcessAggregate chatProcess, UserAccountQuotaEntity data) throws Exception {
//
// if(data.getIntegral()<chatProcess.getModelConsumer() * chatProcess.getTokenNum()){
// return RuleLogicEntity.<MusicProcessAggregate>builder()
// .info("积分不足,请及时充值")
// .type(LogicCheckEnum.REFUSE)
// .data(chatProcess).build();
// }
//
// return RuleLogicEntity.<MusicProcessAggregate>builder()
// .type(LogicCheckEnum.SUCCESS).data(chatProcess).build();
// }
//
//
//}

@ -1,69 +0,0 @@
package com.ruoyi.system.ai.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.List;
public class DocumentReaderUtils {
public static String readDocument(File file) {
if(file.length()>200 *1024){
return "文件过大";
}
String content = "";
String extension = file.getName().substring(file.getName().lastIndexOf('.') + 1).toLowerCase();
System.out.println(extension);
try {
switch (extension) {
case "txt":
case "md":
case "csv":
case "markdown":
// 对于文本文件,可以直接读取内容
List<String> lines = java.nio.file.Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
content = String.join("\n", lines);
break;
case "docx":
// 对于Word文档使用Apache POI库
try (XWPFDocument docxDocument = new XWPFDocument(OPCPackage.open(file))) {
StringBuilder contentBuilder = new StringBuilder();
for (XWPFParagraph paragraph : docxDocument.getParagraphs()) {
contentBuilder.append(paragraph.getText()).append("\n");
}
content = contentBuilder.toString();
}
break;
case "pdf":
// 对于PDF文档使用PDFBox库
try (PDDocument pdfDocument = PDDocument.load(file)) {
PDFTextStripper stripper = new PDFTextStripper();
content = stripper.getText(pdfDocument);
}
break;
// 可以根据需要添加更多文件类型和相应的处理逻辑
default:
content = "Unsupported file type";
}
} catch (IOException | InvalidFormatException e) {
content = "Error reading file: " + e.getMessage();
e.printStackTrace();
}
return content;
}
public static void main(String[] args) {
File file = new File("C:\\Users\\weizh\\Desktop\\packageIO.csv"); // 替换为实际文件路径
String documentContent = readDocument(file);
System.out.println(documentContent);
}
}

@ -1,154 +0,0 @@
package com.ruoyi.system.ai.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.muta.ai.domain.dto.MessageHistoryKimi;
import lombok.NonNull;
import lombok.SneakyThrows;
import okhttp3.*;
import java.io.BufferedReader;
import java.io.File;
import java.util.List;
import java.util.Optional;
public class MoonshotAiUtils {
private static final String API_KEY = "sk-SgNVCgBxkVPVHjINo708cqiuXPNMNKWdT2JORNkika6FOAht";
private static final String MODELS_URL = "https://api.moonshot.cn/v1/models";
private static final String FILES_URL = "https://api.moonshot.cn/v1/files";
private static final String ESTIMATE_TOKEN_COUNT_URL = "https://api.moonshot.cn/v1/tokenizers/estimate-token-count";
private static final String CHAT_COMPLETION_URL = "https://api.moonshot.cn/v1/chat/completions";
private static final String CHECK_BALANCE ="https://api.moonshot.cn/v1/users/me/balance";
public static String getModelList() {
return getCommonRequest(MODELS_URL)
.execute()
.body();
}
public static String getBalance() {
return getCommonRequest(CHECK_BALANCE)
.execute()
.body();
}
public static String getBalanceByKey(String key) {
return getCommonRequestByKey(CHECK_BALANCE, key)
.execute()
.body();
}
public static String uploadFile(@NonNull File file) {
return getCommonRequest(FILES_URL)
.method(Method.POST)
.header("purpose", "file-extract")
.form("file", file)
.execute()
.body();
}
public static String getFileList() {
return getCommonRequest(FILES_URL)
.execute()
.body();
}
public static String deleteFile(@NonNull String fileId) {
return getCommonRequest(FILES_URL + "/" + fileId)
.method(Method.DELETE)
.execute()
.body();
}
public static String getFileDetail(@NonNull String fileId) {
return getCommonRequest(FILES_URL + "/" + fileId)
.execute()
.body();
}
public static String getFileContent(@NonNull String fileId) {
return getCommonRequest(FILES_URL + "/" + fileId + "/content")
.execute()
.body();
}
public static String estimateTokenCount(@NonNull String model, @NonNull List<MessageHistoryKimi> messages) {
String requestBody = new JSONObject()
.putOpt("model", model)
.putOpt("messages", messages)
.toString();
return getCommonRequest(ESTIMATE_TOKEN_COUNT_URL)
.method(Method.POST)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
.body(requestBody)
.execute()
.body();
}
@SneakyThrows
public static void chat(@NonNull String model, @NonNull List<MessageHistoryKimi> messages) {
String requestBody = new JSONObject()
.putOpt("model", model)
.putOpt("messages", messages)
.putOpt("stream", true)
.toString();
Request okhttpRequest = new Request.Builder()
.url(CHAT_COMPLETION_URL)
.post(RequestBody.create(MediaType.get(ContentType.JSON.getValue()), requestBody))
.addHeader("Authorization", "Bearer " + API_KEY)
.build();
Call call = new OkHttpClient().newCall(okhttpRequest);
Response okhttpResponse = call.execute();
BufferedReader reader = new BufferedReader(okhttpResponse.body().charStream());
String line;
StringBuffer content = new StringBuffer();
while ((line = reader.readLine()) != null) {
if (StrUtil.isBlank(line)) {
continue;
}
if (JSONUtil.isTypeJSON(line)) {
Optional.of(JSONUtil.parseObj(line))
.map(x -> x.getJSONObject("error"))
.map(x -> x.getStr("message"))
.ifPresent(x -> System.out.println("error: " + x));
return;
}
line = StrUtil.replace(line, "data: ", StrUtil.EMPTY);
if (StrUtil.equals("[DONE]", line) || !JSONUtil.isTypeJSON(line)) {
System.out.println(content);
return;
}
Optional.of(JSONUtil.parseObj(line))
.map(x -> x.getJSONArray("choices"))
.filter(CollUtil::isNotEmpty)
.map(x -> (JSONObject) x.get(0))
.map(x -> x.getJSONObject("delta"))
.map(x -> x.getStr("content"))
.ifPresent(x ->{
System.out.println("rowData: " + x);
content.append(x);
} );
}
}
private static HttpRequest getCommonRequest(@NonNull String url) {
return HttpRequest.of(url).header(Header.AUTHORIZATION, "Bearer " + API_KEY);
}
private static HttpRequest getCommonRequestByKey(@NonNull String url, @NonNull String key) {
return HttpRequest.of(url).header(Header.AUTHORIZATION, "Bearer " + key);
}
public static void main(String[] args) {
}
}

@ -1,69 +0,0 @@
package com.ruoyi.system.aipay;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.FileItem;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.muta.pay.config.AliPayConfig;
import java.util.Base64;
import java.util.ArrayList;
import java.util.List;
public class AlipaySystemOauthToken {
public static void main(String[] args) throws AlipayApiException {
// AlipayClient alipayClient1 = AliPayConfig.getInstance();
// AlipayUserInfoShareRequest request1 = new AlipayUserInfoShareRequest();
// AlipayUserInfoShareResponse response1 = alipayClient1.execute(request1,accessToken);
// if(response1.isSuccess()){
// System.out.println("调用成功");
// } else {
// System.out.println("调用失败");
// }
// 初始化SDK
AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
// 构造请求参数以调用接口
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
// // 设置刷新令牌
// request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
//
// // 设置授权码
// request.setCode("4b203fe6c11548bcabd8da5bb087a83b");
// 设置授权方式
request.setGrantType("authorization_code");
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
System.out.println(response.getBody());
if (response.isSuccess()) {
System.out.println("调用成功");
} else {
System.out.println("调用失败");
// sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
// String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
// System.out.println(diagnosisUrl);
}
}
private static AlipayConfig getAlipayConfig() {
AlipayConfig alipayConfig = new AlipayConfig();
alipayConfig.setServerUrl(AliPayConfig.PAY_GATEWAY);
alipayConfig.setAppId(AliPayConfig.APPID);
alipayConfig.setPrivateKey(AliPayConfig.APP_PRI_KEY);
alipayConfig.setFormat("json");
alipayConfig.setAlipayPublicKey(AliPayConfig.APP_PUB_KEY);
alipayConfig.setCharset("UTF-8");
alipayConfig.setSignType("RSA2");
return alipayConfig;
}
}

@ -1,13 +0,0 @@
package com.ruoyi.system.aipay;
/**
* @author: Larry
* @Date: 2024 /08 /01 / 16:15
* @Description:
*/
public class TestLogin {
public void test(){
}
}

@ -1,19 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 访
*
* @author ruoyi
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Anonymous
{
}

@ -1,33 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope
{
/**
*
*/
public String deptAlias() default "";
/**
*
*/
public String userAlias() default "";
/**
* @ss
*/
public String permission() default "";
}

File diff suppressed because it is too large Load Diff

@ -1,197 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import com.ruoyi.common.utils.poi.ExcelHandlerAdapter;
/**
* Excel
*
* @author ruoyi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
/**
* excel
*/
public int sort() default Integer.MAX_VALUE;
/**
* Excel.
*/
public String name() default "";
/**
* , : yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* type (: sys_user_sex)
*/
public String dictType() default "";
/**
* (: 0=,1=,2=)
*/
public String readConverterExp() default "";
/**
*
*/
public String separator() default ",";
/**
* BigDecimal :-1(BigDecimal)
*/
public int scale() default -1;
/**
* BigDecimal :BigDecimal.ROUND_HALF_EVEN
*/
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
/**
* excel
*/
public double height() default 14;
/**
* excel
*/
public double width() default 16;
/**
* ,% 90 90%
*/
public String suffix() default "";
/**
* ,
*/
public String defaultValue() default "";
/**
*
*/
public String prompt() default "";
/**
*
*/
public boolean wrapText() default false;
/**
* .
*/
public String[] combo() default {};
/**
* combo,,dictType.
*/
public boolean comboReadDict() default false;
/**
* ,:list)
*/
public boolean needMerge() default false;
/**
* ,:,.
*/
public boolean isExport() default true;
/**
* ,,
*/
public String targetAttr() default "";
/**
* ,
*/
public boolean isStatistics() default false;
/**
* 0 1 2
*/
public ColumnType cellType() default ColumnType.STRING;
/**
*
*/
public IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT;
/**
*
*/
public IndexedColors headerColor() default IndexedColors.WHITE;
/**
*
*/
public IndexedColors backgroundColor() default IndexedColors.WHITE;
/**
*
*/
public IndexedColors color() default IndexedColors.BLACK;
/**
*
*/
public HorizontalAlignment align() default HorizontalAlignment.CENTER;
/**
*
*/
public Class<?> handler() default ExcelHandlerAdapter.class;
/**
*
*/
public String[] args() default {};
/**
* 012
*/
Type type() default Type.ALL;
public enum Type
{
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
public enum ColumnType
{
NUMERIC(0), STRING(1), IMAGE(2), TEXT(3);
private final int value;
ColumnType(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
}

@ -1,18 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel
*
* @author ruoyi
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels
{
public Excel[] value();
}

@ -1,51 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OperatorType;
/**
*
*
* @author ruoyi
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/**
*
*/
public String title() default "";
/**
*
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
*
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
*
*/
public boolean isSaveRequestData() default true;
/**
*
*/
public boolean isSaveResponseData() default true;
/**
*
*/
public String[] excludeParamNames() default {};
}

@ -1,40 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.enums.LimitType;
/**
*
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter
{
/**
* key
*/
public String key() default CacheConstants.RATE_LIMIT_KEY;
/**
* ,
*/
public int time() default 60;
/**
*
*/
public int count() default 100;
/**
*
*/
public LimitType limitType() default LimitType.DEFAULT;
}

@ -1,31 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*
* @author ruoyi
*
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit
{
/**
* (ms)
*/
public int interval() default 5000;
/**
*
*/
public String message() default "不允许重复提交,请稍候再试";
}

@ -1,24 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ruoyi.common.config.serializer.SensitiveJsonSerializer;
import com.ruoyi.common.enums.DesensitizedType;
/**
*
*
* @author ruoyi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = SensitiveJsonSerializer.class)
public @interface Sensitive
{
DesensitizedType desensitizedType();
}

@ -1,72 +0,0 @@
package com.ruoyi.system.basics.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.muta.common.core.MutaBaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @author
* @Date: 2024/04/20/16:22
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Kamil extends MutaBaseEntity {
/**
* id
*/
@TableId(type = IdType.AUTO)
@JsonFormat(shape =JsonFormat.Shape.STRING)
private Long id;
/**
* 使使ip
*/
private String ip;
/**
* 使id
*/
@JsonFormat(shape =JsonFormat.Shape.STRING)
private Long userId;
/**
*
*/
@TableField(value = "`key`")
private String key;
/**
* type0
* type1
* typesvip2svip
*/
private Integer value;
/**
* 0 1使
*/
private Integer status;
/**
* 0 1 2svip
*/
private Integer type;
/**
*
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
}

@ -1,34 +0,0 @@
package com.ruoyi.system.basics.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author
* @Date: 2024/04/21/20:24
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class KamilAddDTO {
/**
* 0 1 2
*/
private Integer type;
/**
* type
* type0 type12
*/
private Integer value;
/**
*
*/
private Integer quantity;
}

@ -1,25 +0,0 @@
package com.ruoyi.system.basics.domain.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @author
* @Date: 2024/05/06/16:36
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class KamilConDefDTO {
private String key;
private Integer value;
private Integer type;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
}

@ -1,12 +0,0 @@
package com.ruoyi.system.basics.factory.kamil;
import com.muta.basics.domain.Kamil;
/**
* @author
* @Date: 2024/04/22/19:45
*/
public interface KamilConsumption {
void consumption(Kamil kamil);
}

@ -1,37 +0,0 @@
package com.ruoyi.system.basics.factory.kamil;
import com.muta.basics.factory.kamil.impl.SvipKamilConsumption;
import com.muta.basics.factory.kamil.impl.VipKamilConsumption;
import com.muta.basics.factory.kamil.impl.IntegrationKamilConsumption;
import com.muta.basics.domain.Kamil;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author
* @Date: 2024/04/22/18:31
*/
@Service
public class KamilTypeFactory {
public Map<Integer, KamilConsumption> kamilConsumptionMap = new ConcurrentHashMap<>();
@Resource
private IntegrationKamilConsumption integrationKamilConsumption;
@Resource
private VipKamilConsumption vipKamilConsumption;
@Resource
private SvipKamilConsumption svipKamilConsumption;
@PostConstruct
public void init() {
kamilConsumptionMap.put(0, integrationKamilConsumption);
kamilConsumptionMap.put(1, vipKamilConsumption);
kamilConsumptionMap.put(2, svipKamilConsumption);
}
public void consumption(Kamil kamil) {
KamilConsumption kamilConsumption = kamilConsumptionMap.get(kamil.getType());
kamilConsumption.consumption(kamil);
}
}

@ -1,36 +0,0 @@
package com.ruoyi.system.basics.factory.kamil.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.muta.basics.factory.kamil.KamilConsumption;
import com.muta.common.annotation.IntegralLogInsert;
import com.muta.common.constant.OperationConstants;
import com.muta.common.core.domain.entity.UserExtra;
import com.muta.common.utils.SecurityUtils;
import com.muta.basics.domain.Kamil;
import com.muta.system.mapper.UserExtraMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author
* @Date: 2024/04/22/19:48
*/
@Service
public class IntegrationKamilConsumption implements KamilConsumption {
@Resource
private UserExtraMapper userExtraMapper;
@Override
@IntegralLogInsert(operation = OperationConstants.Kamil)
public void consumption(Kamil kamil) {
LambdaQueryWrapper<UserExtra> lqw = new LambdaQueryWrapper<>();
lqw.eq(UserExtra::getUserId, SecurityUtils.getUserId());
UserExtra userExtra = userExtraMapper.selectOne(lqw);
Integer value = kamil.getValue();
userExtra.setIntegral(userExtra.getIntegral() + value);
userExtraMapper.updateById(userExtra);
}
}

@ -1,53 +0,0 @@
package com.ruoyi.system.basics.factory.kamil.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.muta.basics.factory.kamil.KamilConsumption;
import com.muta.common.annotation.IntegralLogInsert;
import com.muta.common.constant.OperationConstants;
import com.muta.common.core.domain.entity.UserExtra;
import com.muta.common.utils.SecurityUtils;
import com.muta.basics.domain.Kamil;
import com.muta.system.domain.Vip;
import com.muta.system.mapper.UserExtraMapper;
import com.muta.system.mapper.VipMapper;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
/**
* @author
* @Date: 2024/04/22/19:49
*/
@Component
public class SvipKamilConsumption implements KamilConsumption {
@Resource
private VipMapper vipMapper;
@Override
@IntegralLogInsert(operation = OperationConstants.Kamil)
public void consumption(Kamil kamil) {
LambdaQueryWrapper<Vip> lqw = new LambdaQueryWrapper<>();
lqw.eq(Vip::getUserId, SecurityUtils.getUserId());
Vip vip = vipMapper.selectOne(lqw);
Integer value = kamil.getValue();
Date now = new Date();
Date svipExpireTime = vip.getSvipExpireTime();
Calendar calendar = Calendar.getInstance();
//首先判断用户当前是不是svip 若是则在截止日期后加上value天
if (null != svipExpireTime && svipExpireTime.after(now))
calendar.setTime(vip.getVipExpireTime());
else {
//若不是 则在从今天开始加上value天 作为截止日期 并更新开始时间为今日
calendar.setTime(now);
vip.setSvipBeginTime(now);
}
calendar.add(Calendar.DAY_OF_YEAR, value);
vip.setSvipExpireTime(calendar.getTime());
vipMapper.updateById(vip);
}
}

@ -1,53 +0,0 @@
package com.ruoyi.system.basics.factory.kamil.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.muta.basics.factory.kamil.KamilConsumption;
import com.muta.common.annotation.IntegralLogInsert;
import com.muta.common.constant.OperationConstants;
import com.muta.common.core.domain.entity.UserExtra;
import com.muta.common.utils.SecurityUtils;
import com.muta.basics.domain.Kamil;
import com.muta.system.domain.Vip;
import com.muta.system.mapper.UserExtraMapper;
import com.muta.system.mapper.VipMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
/**
* @author
* @Date: 2024/04/22/19:49
*/
@Service
public class VipKamilConsumption implements KamilConsumption {
@Resource
private UserExtraMapper userExtraMapper;
@Resource
private VipMapper vipMapper;
@Override
@IntegralLogInsert(operation = OperationConstants.Kamil)
public void consumption(Kamil kamil) {
LambdaQueryWrapper<Vip> lqw = new LambdaQueryWrapper<>();
lqw.eq(Vip::getUserId, SecurityUtils.getUserId());
Vip vip = vipMapper.selectOne(lqw);
Integer value = kamil.getValue();
Date now = new Date();
Date vipExpireTime = vip.getVipExpireTime();
Calendar expCalendar = Calendar.getInstance();
//首先判断用户当前是不是svip 若是则在截止日期后加上value天
if (null != vipExpireTime && vipExpireTime.after(now))
expCalendar.setTime(vip.getVipExpireTime());
else {
//若不是 则在从今天开始加上value天 作为截止日期 并更新开始日期为今日
expCalendar.setTime(now);
vip.setVipBeginTime(now);
}
expCalendar.add(Calendar.DAY_OF_YEAR, value);
vip.setVipExpireTime(expCalendar.getTime());
vipMapper.updateById(vip);
}
}

@ -1,64 +0,0 @@
package com.ruoyi.system.basics.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.muta.basics.domain.Kamil;
import java.util.List;
/**
* Mapper
*
* @author mutaai
* @date 2024-04-21
*/
public interface KamilMapper extends BaseMapper<Kamil> {
/**
*
*
* @param id
* @return
*/
public Kamil selectKamilById(String id);
/**
*
*
* @param kamil
* @return
*/
public List<Kamil> selectKamilList(Kamil kamil);
/**
*
*
* @param kamil
* @return
*/
public int insertKamil(Kamil kamil);
/**
*
*
* @param kamil
* @return
*/
public int updateKamil(Kamil kamil);
/**
*
*
* @param id
* @return
*/
public int deleteKamilById(String id);
/**
*
*
* @param ids
* @return
*/
public int deleteKamilByIds(String[] ids);
}

@ -1,72 +0,0 @@
package com.ruoyi.system.basics.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.muta.common.core.domain.AjaxResult;
import com.muta.basics.domain.Kamil;
import com.muta.basics.domain.dto.KamilAddDTO;
import com.muta.basics.domain.dto.KamilConDefDTO;
import java.util.List;
/**
* Service
*
* @author mutaai
* @date 2024-04-21
*/
public interface IKamilService extends IService<Kamil> {
/**
*
*
* @param id
* @return
*/
public Kamil selectKamilById(String id);
/**
*
*
* @param kamil
* @return
*/
public List<Kamil> selectKamilList(Kamil kamil);
/**
*
*
* @param kamil
* @return
*/
public int insertKamil(Kamil kamil);
/**
*
*
* @param kamil
* @return
*/
public int updateKamil(Kamil kamil);
/**
*
*
* @param ids
* @return
*/
public int deleteKamilByIds(String[] ids);
/**
*
*
* @param id
* @return
*/
public int deleteKamilById(String id);
void addBatch(KamilAddDTO kamilAddDTO);
AjaxResult use(String key);
AjaxResult conDef(KamilConDefDTO kamilConDefDTO);
}

@ -1,190 +0,0 @@
package com.ruoyi.system.basics.service.impl;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muta.common.annotation.RepeatSubmit;
import com.muta.common.core.domain.AjaxResult;
import com.muta.common.utils.DateUtils;
import com.muta.common.utils.SecurityUtils;
import com.muta.basics.domain.dto.KamilConDefDTO;
import com.muta.basics.factory.kamil.KamilTypeFactory;
import com.muta.basics.domain.Kamil;
import com.muta.basics.domain.dto.KamilAddDTO;
import com.muta.basics.mapper.KamilMapper;
import com.muta.basics.service.IKamilService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import static com.muta.common.constant.CacheConstants.KAMIL_KEY;
/**
* Service
*
* @author mutaai
* @date 2024-04-21
*/
@Service
public class KamilServiceImpl extends ServiceImpl<KamilMapper, Kamil> implements IKamilService {
@Resource
private KamilMapper kamilMapper;
@Resource
private KamilTypeFactory kamilTypeFactory;
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
*
*
* @param id
* @return
*/
@Override
public Kamil selectKamilById(String id) {
return kamilMapper.selectKamilById(id);
}
/**
*
*
* @param kamil
* @return
*/
@Override
public List<Kamil> selectKamilList(Kamil kamil) {
return kamilMapper.selectList(new LambdaQueryWrapper<>());
}
/**
*
*
* @param kamil
* @return
*/
@Override
public int insertKamil(Kamil kamil) {
kamil.setCreateTime(DateUtils.getNowDate());
return kamilMapper.insertKamil(kamil);
}
/**
*
*
* @param kamil
* @return
*/
@Override
public int updateKamil(Kamil kamil) {
kamil.setUpdateTime(DateUtils.getNowDate());
return kamilMapper.updateKamil(kamil);
}
/**
*
*
* @param ids
* @return
*/
@Override
public int deleteKamilByIds(String[] ids) {
return kamilMapper.deleteKamilByIds(ids);
}
/**
*
*
* @param id
* @return
*/
@Override
public int deleteKamilById(String id) {
return kamilMapper.deleteKamilById(id);
}
@Override
@Transactional
public void addBatch(KamilAddDTO kamilAddDTO) {
int n = kamilAddDTO.getQuantity();
Kamil kamil = new Kamil();
kamil.setType(kamilAddDTO.getType());
kamil.setValue(kamilAddDTO.getValue());
//生成n个卡密
for (int i = 0; i < n; i++) {
//卡密的key为对当前时间戳进行md5加密获得的32位字符串
kamil.setKey(MD5.create().digestHex(String.valueOf(System.currentTimeMillis())));
kamilMapper.insert(kamil);
}
}
@Override
@RepeatSubmit
public AjaxResult use(String key) {
Long userId = SecurityUtils.getUserId();
LambdaQueryWrapper<Kamil> lqw = new LambdaQueryWrapper<>();
lqw.eq(Kamil::getKey, key);
//根据用户输入的key查找卡密 对其存在与否以及状态进行判断
Kamil kamil = kamilMapper.selectOne(lqw);
System.out.println(kamil);
if (ObjUtil.isEmpty(kamil))
return AjaxResult.error("卡密不存在");
if (kamil.getEndTime() == null) {
if (kamil.getStatus() == 1)
return AjaxResult.error("卡密已被使用");
//校验通过 修改数据库卡密状态
kamil.setStatus(1);
kamil.setUserId(userId);
kamilMapper.updateById(kamil);
} else {
//是存在截止时间的自定义卡密
if (kamil.getEndTime().before(new Date())) {
//判断是否已过期
if (kamil.getStatus() == 0) {
//过期 且status为0 则将其status设置为1 并将该key从redis中删除
kamil.setStatus(1);
stringRedisTemplate.delete(KAMIL_KEY + key);
kamilMapper.updateById(kamil);
}
return AjaxResult.error("卡密已过期");
}
//该卡密未过期 判断该用户是否使用过 也就是判断以该卡密的key为 key的set列表中有没有该用户的userId 若有 则使用过
if (Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(KAMIL_KEY + key, userId.toString()))) {
return AjaxResult.error("您已使用过该卡密");
} else {
//没使用过该卡密 将用户id添加到set列表中
stringRedisTemplate.opsForSet().add(KAMIL_KEY + key, userId.toString());
}
}
//调用工厂 消耗卡密 为用户增加相应的值
kamilTypeFactory.consumption(kamil);
return AjaxResult.success();
}
@Override
public AjaxResult conDef(KamilConDefDTO kamilConDefDTO) {
Kamil kamil = new Kamil();
LambdaQueryWrapper<Kamil> lqw = new LambdaQueryWrapper<>();
lqw.eq(Kamil::getKey, kamilConDefDTO.getKey()); //构建查询条件 查询卡密的key是否被占用
if (ObjectUtil.isNotEmpty(kamilMapper.selectList(lqw))) {
return AjaxResult.error("卡密已存在"); //卡密已存在 返回错误信息 生成失败
};
//校验成功 将dto中的值拷贝到kamil对象中
kamil.setKey(kamilConDefDTO.getKey());
kamil.setValue(kamilConDefDTO.getValue());
kamil.setType(kamilConDefDTO.getType());
kamil.setEndTime(kamilConDefDTO.getEndTime());
//新增
kamilMapper.insert(kamil);
return AjaxResult.success();
}
}

@ -1,122 +0,0 @@
package com.ruoyi.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
*
*
* @author ruoyi
*/
@Component
@ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig
{
/** 项目名称 */
private String name;
/** 版本 */
private String version;
/** 版权年份 */
private String copyrightYear;
/** 上传路径 */
private static String profile;
/** 获取地址开关 */
private static boolean addressEnabled;
/** 验证码类型 */
private static String captchaType;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
public String getCopyrightYear()
{
return copyrightYear;
}
public void setCopyrightYear(String copyrightYear)
{
this.copyrightYear = copyrightYear;
}
public static String getProfile()
{
return profile;
}
public void setProfile(String profile)
{
RuoYiConfig.profile = profile;
}
public static boolean isAddressEnabled()
{
return addressEnabled;
}
public void setAddressEnabled(boolean addressEnabled)
{
RuoYiConfig.addressEnabled = addressEnabled;
}
public static String getCaptchaType() {
return captchaType;
}
public void setCaptchaType(String captchaType) {
RuoYiConfig.captchaType = captchaType;
}
/**
*
*/
public static String getImportPath()
{
return getProfile() + "/import";
}
/**
*
*/
public static String getAvatarPath()
{
return getProfile() + "/avatar";
}
/**
*
*/
public static String getDownloadPath()
{
return getProfile() + "/download/";
}
/**
*
*/
public static String getUploadPath()
{
return getProfile() + "/upload";
}
}

@ -1,67 +0,0 @@
package com.ruoyi.common.config.serializer;
import java.io.IOException;
import java.util.Objects;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.ruoyi.common.annotation.Sensitive;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.DesensitizedType;
import com.ruoyi.common.utils.SecurityUtils;
/**
*
*
* @author ruoyi
*/
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer
{
private DesensitizedType desensitizedType;
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException
{
if (desensitization())
{
gen.writeString(desensitizedType.desensitizer().apply(value));
}
else
{
gen.writeString(value);
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
throws JsonMappingException
{
Sensitive annotation = property.getAnnotation(Sensitive.class);
if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass()))
{
this.desensitizedType = annotation.desensitizedType();
return this;
}
return prov.findValueSerializer(property.getType(), property);
}
/**
*
*/
private boolean desensitization()
{
try
{
LoginUser securityUser = SecurityUtils.getLoginUser();
// 管理员不脱敏
return !securityUser.getUser().isAdmin();
}
catch (Exception e)
{
return true;
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save