12 Commits
Author SHA1 Message Date
hello-hao 733ec3e6f9 :rocket:修改配置文件,支持Docker部署 2023-03-21 21:15:31 +08:00
hello-hao c3e91f3593 :rocket:优化代码 2023-03-20 18:06:00 +08:00
hello-hao 8ebdbf6cee update:调整数据类型,删除逻辑
feat:sout在log文件中显示
2023-03-17 17:41:10 +08:00
hello-hao 393ad3138e update:调整了百度鉴别接口升级了依赖,新增了key的相关字段信息 2023-03-16 17:38:01 +08:00
hello-hao 6f6166275a feat:新增对接S3协议
style:调整日志框架
docs:调整了文档
2023-03-15 17:35:04 +08:00
hello-hao cc05712906 :rocket:修改存储源 2023-03-15 10:20:55 +08:00
hello-hao e61b7ce10d 📝 修改文件 2023-03-05 23:08:17 +08:00
hello-hao 1408b9c029 📝 修改文件 2023-03-05 14:28:34 +08:00
hello-hao f56bc84d29 :art:修改系统配置表数据结构,添加数据库连接检测 2023-03-03 18:59:12 +08:00
hello-hao f8a712e601 📝 2023-02-28 17:44:28 +08:00
hello-hao 4ca9159956 📝 修改文件 2023-01-01 23:27:08 +08:00
hello-hao 2048660b64 :rocket:修复筛选出现重复,记录图片原始名称等多个问题 2023-01-01 23:20:37 +08:00
50 changed files with 1145 additions and 1513 deletions
+14 -8
View File
@@ -10,7 +10,7 @@
### 引导
[官网](https://tbed.hellohao.cn) | [宣传视频](https://www.bilibili.com/video/BV11r4y1y7mH/) | [文档](https://doc.hellohao.cn) | [演示站](https://pic.hellohao.cn) | [前端源码](https://github.com/Hello-hao/tbed-web) | [桌面客户端](https://tbed.hellohao.cn/app)
[官网](https://tbed.hellohao.cn) | [论坛](http://bbs.hellohao.cn) | [文档](https://doc.hellohao.cn) | [演示站](https://pic.hellohao.cn) | [桌面客户端](https://tbed.hellohao.cn/app) | [前端源码](https://github.com/Hello-hao/tbed-web)
### 前言
@@ -26,12 +26,18 @@
Core版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,~~`U-File`~~,`FTP`,`Backblaze(B2)`,`百度云BOS`,`青云Qingstor`,`Ucloud US3`,`Minio`,`AWS S3`等通用S3协议
### 更新日志 `20221027`
### 更新日志 `20230101`
- 优化个人相册,适配右键菜单功能。
- 修复筛选全部图片时候出现重复的问题。
- 修复上传图片后不记录图片原始名称
- 调整了上传图像的代码逻辑
- 优化 ftp 上传逻辑
- 优化多线程上传图像的查重逻辑
- 新增用户协议相关协议内容展示
- 提高系统安全性
- 优化多个页面异常问题
- `修复`部分场景下登录或者注册时出现验证码一直不正确的问题
- `调整`URL转存时提示登陆的限制
- `优化`服务端返回值的一些问题
[^_^]:程序宣传视频:[自制宣传视频](https://www.bilibili.com/video/BV11r4y1y7mH/)
@@ -182,8 +188,8 @@ Core版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,
### 反馈交流
**如果你遇到BUG欢迎反馈**
欢迎加入Hellohao开发者交流群,群聊号码:**864800972**
- 前往论坛发帖反馈、求助:[Hellohao开发者交流论坛](http://bbs.hellohao.cn)
- 也可加QQ群探讨(目前已满):864800972
### 捐赠开发者
+17
View File
@@ -0,0 +1,17 @@
FROM openjdk:8
MAINTAINER 923453645@qq.com
ADD hellohaotbed/ /hellohaotbed
COPY appstart.sh /appstart.sh
COPY application.properties /application.properties
COPY Tbed.jar /Tbed.jar
EXPOSE 10088
EXPOSE 10089
CMD ["/bin/bash","/appstart.sh"]
+11 -7
View File
@@ -90,11 +90,11 @@
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>commons-logging</groupId>-->
<!-- <artifactId>commons-logging</artifactId>-->
<!-- <version>1.2</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
@@ -120,7 +120,11 @@
<artifactId>pebble</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.334</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
@@ -130,7 +134,7 @@
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.11.0</version>
<version>4.16.14</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
+5 -5
View File
@@ -11,7 +11,7 @@
Target Server Version : 80028
File Encoding : 65001
Date: 01/09/2022 00:28:28
Date: 01/01/2023 23:02:40
*/
SET NAMES utf8mb4;
@@ -99,7 +99,7 @@ CREATE TABLE `config` (
-- ----------------------------
-- Records of config
-- ----------------------------
INSERT INTO `config` VALUES (1, 7, 1, 'Hellohao图床', 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/books_x264.mp4http://cdn.wwery.com/Hellohao/439550606022825.jpg', '1', '<p style=\"color:#7c7c88;\">&copy; 2019 <a href=\"http://www.Hellohao.cn/\" target=\"_blank\" title=\"Hellohao\">Hellohao</a><span>&nbsp;&nbsp;- All Rights Reserved</span> </p>', '也许...|这将是最好用的图床|为了更好的用户体验,建议您注册本站继续免费使用Hellohao图床。本站不得上传任何形式的非法图片,一旦发现,永久删除并禁封账户。情节严重者将相关资料交于相关部门处理。', 'var _hmt = _hmt || [];\n(function() {\n var hm = document.createElement(\"script\");\n hm.src = \"https://hm.baidu.com/hm.js?16c326e608c984c9bae6a63eda861888\";\n var s = document.getElementsByTagName(\"script\")[0]; \n s.parentNode.insertBefore(hm, s);\n})();\n\n', 'http://api.hellohao.cn', '', 'http://cdn.wwery.com/Hellohao/3e1901120091153.jpg', 1, 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'hellohao图床,图床,图片上传,开源图床,hellohao,图像托管,图片分享', 'https://hellohao.nos-eastchina1.126.net/BlogImg/favicon.ico', 2, '这将是你用过最优秀的图像托管程序', NULL, '<img width=\"300px\" src=\"http://img.wwery.com/Hellohao/rPscRYwz.png\">\n <br />\n <br />\n <p>也许,这将是你用到最优秀的图像托管程序</p>\n <p>本程序为Hellohao图象托管程序</p>\n <br/>\n <p style=\"color: #656565;\">作者:hellohao独立开发</p>\n <p style=\"color: #656565;\">www.hellohao.cn</p>');
INSERT INTO `config` VALUES (1, 7, 1, 'Hellohao图床', 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/books_x264.mp4http://cdn.wwery.com/Hellohao/439550606022825.jpg', '1', '<p style=\"color:#7c7c88;\">版权所有&copy;<a href=\"http://tbed.Hellohao.cn/\" target=\"_blank\" title=\"Hellohao\">Hellohao图像托管</a><span>&nbsp;2019- 2023 </span> </p>', '也许...|这将是最好用的图床|为了更好的用户体验,建议您注册本站继续免费使用Hellohao图床。本站不得上传任何形式的非法图片,一旦发现,永久删除并禁封账户。情节严重者将相关资料交于相关部门处理。', 'var _hmt = _hmt || [];\n(function() {\n var hm = document.createElement(\"script\");\n hm.src = \"https://hm.baidu.com/hm.js?16c326e608c984c9bae6a63eda861888\";\n var s = document.getElementsByTagName(\"script\")[0]; \n s.parentNode.insertBefore(hm, s);\n})();\n\n', 'http://api.hellohao.cn', '', 'http://cdn.wwery.com/Hellohao/3e1901120091153.jpg', 1, 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'hellohao图床,图床,图片上传,开源图床,hellohao,图像托管,图片分享', 'https://hellohao.nos-eastchina1.126.net/BlogImg/favicon.ico', 2, '这将是你用过最优秀的图像托管程序', NULL, '<img width=\"300px\" src=\"http://img.wwery.com/Hellohao/rPscRYwz.png\">\n <br />\n <br />\n <p>也许,这将是你用到最优秀的图像托管程序</p>\n <p>本程序为Hellohao图象托管程序</p>\n <br/>\n <p style=\"color: #656565;\">作者:hellohao独立开发</p>\n <p style=\"color: #656565;\">www.hellohao.cn</p>');
-- ----------------------------
-- Table structure for emailconfig
@@ -292,7 +292,7 @@ INSERT INTO `uploadconfig` VALUES (1, '10485760', '20971520', 5, 10, 'gif,jpg,jp
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
@@ -309,7 +309,7 @@ CREATE TABLE `user` (
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', 'YWRtaW4=', 'admin', '2019-01-10', 2, '9b76655b2706483780bf54988ca12531', 1, '2147483648', 1, '');
INSERT INTO `user` VALUES (1, 'admin', 'YWRtaW4=', 'admin', '2019-01-10', 2, '05bc9cdc2d454ab59e9cd7eaa9ed296a', 1, '2147483648', 1, '');
-- ----------------------------
-- Table structure for usergroup
@@ -320,7 +320,7 @@ CREATE TABLE `usergroup` (
`userid` int(0) NULL DEFAULT NULL,
`groupid` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of usergroup
+34 -9
View File
@@ -1,24 +1,23 @@
package cn.hellohao;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;
import cn.hellohao.utils.Print;
import cn.hellohao.dao.KeysMapper;
import cn.hellohao.utils.FirstRun;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.support.DatabaseStartupValidator;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.unit.DataSize;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.net.InetAddress;
import java.util.Scanner;
import javax.servlet.MultipartConfigElement;
import javax.sql.DataSource;
import java.util.stream.Stream;
@SpringBootApplication
@Configuration
@@ -30,6 +29,32 @@ public class TbedApplication {
public static void main(String[] args) {
SpringApplication.run(TbedApplication.class, args);
}
//延缓Spring Boot启动时间直到数据库启动的方法
@Bean
public DatabaseStartupValidator databaseStartupValidator(DataSource dataSource) {
DatabaseStartupValidator databaseStartupValidator = new DatabaseStartupValidator();
databaseStartupValidator.setDataSource(dataSource);
databaseStartupValidator.setValidationQuery(DatabaseDriver.POSTGRESQL.getValidationQuery());
return databaseStartupValidator;
}
@Bean
public static BeanFactoryPostProcessor dependsOnPostProcessor() {
return bf -> {
// Let beans that need the database depend on the DatabaseStartupValidator
// like the JPA EntityManagerFactory or Flyway
String[] flyway = bf.getBeanNamesForType(FirstRun.class);
Stream.of(flyway)
.map(bf::getBeanDefinition)
.forEach(it -> it.setDependsOn("databaseStartupValidator"));
String[] jpa = bf.getBeanNamesForType(KeysMapper.class);
Stream.of(jpa)
.map(bf::getBeanDefinition)
.forEach(it -> it.setDependsOn("databaseStartupValidator"));
};
}
/**
* 文件上传配置
* @return
@@ -0,0 +1,44 @@
package cn.hellohao.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.PrintStream;
import java.util.function.Consumer;
@Configuration
public class LogSystemProxy {
private final static Logger log = LoggerFactory.getLogger("proxy.system.log");
@PostConstruct
public void initProxy(){
log.debug("LogSystemProxy init .....");
System.setOut(getLoggerProxy(StdType.OUT));
System.setErr(getLoggerProxy(StdType.ERR));
}
private enum StdType{
OUT(System.out, log::info),
ERR(System.err, log::error),
;
PrintStream stream;
Consumer<String> consumer;
StdType(PrintStream stream,Consumer<String> consumer){
this.stream = stream;
this.consumer = consumer;
}
}
private PrintStream getLoggerProxy(StdType stdType){
return new PrintStream(stdType.stream){
@Override
public void print(String s) {
stdType.stream.print(s);
stdType.consumer.accept(s);
}
};
}
}
@@ -0,0 +1,52 @@
package cn.hellohao.config;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
//线程池
@Configuration
@EnableAsync
public class PoolConfig {
ThreadPoolProperties properties = new ThreadPoolProperties();
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getCorePoolSize());
executor.setMaxPoolSize(properties.getMaxPoolSize());
executor.setQueueCapacity(properties.getQueueCapacity());
executor.setThreadNamePrefix(properties.getThreadNamePrefix());
executor.setKeepAliveSeconds(properties.getKeepAliveTime());
executor.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown());
executor.setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds());
// 设置任务拒绝策略
/**
* 4种
* ThreadPoolExecutor类有几个内部实现类来处理这类情况:
- AbortPolicy 丢弃任务,抛RejectedExecutionException
- CallerRunsPolicy 由该线程调用线程运行。直接调用Runnable的run方法运行。
- DiscardPolicy 抛弃策略,直接丢弃这个新提交的任务
- DiscardOldestPolicy 抛弃旧任务策略,从队列中踢出最先进入队列(最后一个执行)的任务
* 实现RejectedExecutionHandler接口,可自定义处理器
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
@Data
class ThreadPoolProperties {
private int corePoolSize = 5;
private int maxPoolSize = 50;
private int keepAliveTime = 15;
private int queueCapacity = 6;
private String threadNamePrefix = "Tbed-Thread";
private boolean allowCoreThreadTimeout = false;
private boolean waitForTasksToCompleteOnShutdown = false;
private int awaitTerminationSeconds;
}
}
@@ -472,9 +472,9 @@ public class AdminController {
msg.setInfo("为获取到图像信息");
return msg;
}
List<Integer> imgIds = new ArrayList<Integer>();
List<Long> imgIds = new ArrayList<Long>();
for (int i = 0; i < split.length; i++) {
Integer imgid = Integer.valueOf(split[i]);
Long imgid = Long.valueOf(split[i]);
Images image = imgService.selectByPrimaryKey(imgid);
if (!subject.hasRole("admin")) {
if (!image.getUserid().equals(user.getId())) {
@@ -486,7 +486,7 @@ public class AdminController {
if (imgIds.size() == 0) {
msg.setCode("110404");
} else {
deleimages.dele(uuid, imgIds.stream().toArray(Integer[]::new));
deleimages.dele(uuid, imgIds.stream().toArray(Long[]::new));
msg.setCode("200");
}
return msg;
@@ -504,8 +504,10 @@ public class AdminController {
try{
myProgress = JSON.parseObject(iRedisService.getValue(uuid).toString(), MyProgress.class);
}catch (Exception e){ }
msg.setCode("110666");
msg.setInfo("正在执行");
if (null == myProgress) {
jsonObject.put("succ", myProgress.getDelSuccessCount());
jsonObject.put("succ", 0);
jsonObject.put("errorlist", new ArrayList<String>());
jsonObject.put("oklist", new ArrayList<Long>());
jsonObject.put("delover", false);
@@ -514,15 +516,12 @@ public class AdminController {
jsonObject.put("errorlist", myProgress.getDelErrorImgListt());
jsonObject.put("oklist", myProgress.getDelSuccessImgList());
jsonObject.put("delover", myProgress.getDelOCT());
if(myProgress.getDelOCT()==1){
System.out.println("循环遍历的值:"+myProgress.getDelOCT());
msg.setCode("100");
}
}
msg.setData(jsonObject);
if (myProgress.getDelOCT()==1) {
System.out.println("循环遍历的值:" + myProgress.getDelOCT());
msg.setCode("100");
} else {
msg.setCode("110666");
msg.setInfo("正在执行");
}
return msg;
} catch (Exception e) {
e.printStackTrace();
@@ -25,7 +25,7 @@ import java.util.List;
@RequestMapping("/admin/root")
public class AdminRootController {
@Autowired
private ConfigService configService;
private ConfdataService confdataService;
@Autowired
private KeysService keysService;
@Autowired
@@ -194,9 +194,9 @@ public class AdminRootController {
} else if (key.getStorageType() == 6) {
ret = COSImageupload.Initialize(key);
} else if (key.getStorageType() == 7) {
ret = FTPImageupload.Initialize(key);
ret = FtpServiceImpl.Initialize(key);
} else if (key.getStorageType() == 8) {
ret = UFileImageupload.Initialize(key);
ret = S3Imageupload.Initialize(key);
}
Long l = imgService.getsourcememory(keyId);
jsonObject.put("isok", ret);
@@ -219,23 +219,24 @@ public class AdminRootController {
@ResponseBody
public Msg updateStorage(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObj = JSONObject.parseObject(data);
Integer id = jsonObj.getInteger("id");
String AccessKey = jsonObj.getString("AccessKey");
String AccessSecret = jsonObj.getString("AccessSecret");
String Endpoint = jsonObj.getString("Endpoint");
String Bucketname = jsonObj.getString("Bucketname");
String RequestAddress = jsonObj.getString("RequestAddress");
Integer storageType = jsonObj.getInteger("storageType");
String keyname = jsonObj.getString("keyname");
Keys keys = new Keys();
keys.setId(id);
keys.setAccessKey(AccessKey);
keys.setAccessSecret(AccessSecret);
keys.setEndpoint(Endpoint);
keys.setBucketname(Bucketname);
keys.setRequestAddress(RequestAddress);
keys.setStorageType(storageType);
keys.setKeyname(keyname);
// Integer id = jsonObj.getInteger("id");
// String AccessKey = jsonObj.getString("AccessKey");
// String AccessSecret = jsonObj.getString("AccessSecret");
// String Endpoint = jsonObj.getString("Endpoint");
// String Bucketname = jsonObj.getString("Bucketname");
// String RequestAddress = jsonObj.getString("RequestAddress");
// Integer storageType = jsonObj.getInteger("storageType");
// String keyname = jsonObj.getString("keyname");
// Keys keys = new Keys();
// keys.setId(id);
// keys.setAccessKey(AccessKey);
// keys.setAccessSecret(AccessSecret);
// keys.setEndpoint(Endpoint);
// keys.setBucketname(Bucketname);
// keys.setRequestAddress(RequestAddress);
// keys.setStorageType(storageType);
// keys.setKeyname(keyname);
Keys keys = JSON.toJavaObject(jsonObj,Keys.class);
Msg msg = keysService.updateKey(keys);
return msg;
}
@@ -260,7 +261,7 @@ public class AdminRootController {
User u = (User) subject.getPrincipal();
try {
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
Config config = configService.getSourceype();
final Confdata confdata = confdataService.selectConfdata("config");
SysConfig sysConfig = sysConfigService.getstate();
AppClient appClientData = appClientService.getAppClientData("app");
uploadConfig.setUsermemory(Long.toString(Long.valueOf(uploadConfig.getUsermemory()) / 1024 / 1024));
@@ -268,7 +269,7 @@ public class AdminRootController {
uploadConfig.setFilesizetourists(Long.toString(Long.valueOf(uploadConfig.getFilesizetourists()) / 1024 / 1024));
uploadConfig.setFilesizeuser(Long.toString(Long.valueOf(uploadConfig.getFilesizeuser()) / 1024 / 1024));
jsonObject.put("uploadConfig", uploadConfig);
jsonObject.put("config", config);
jsonObject.put("config", JSONObject.parseObject(confdata.getJsondata()));
jsonObject.put("sysConfig", sysConfig);
jsonObject.put("appClient", appClientData);
msg.setData(jsonObject);
@@ -296,7 +297,7 @@ public class AdminRootController {
msg.setCode("500");
return msg;
}
Config config = JSON.toJavaObject((JSON) jsonObject.get("config"), Config.class);
// Config config = JSON.toJavaObject((JSON) jsonObject.get("config"), Config.class);
SysConfig sysConfig = JSON.toJavaObject((JSON) jsonObject.get("sysConfig"), SysConfig.class);
AppClient appClient = JSON.toJavaObject((JSON) jsonObject.get("appClient"), AppClient.class);
if (Integer.valueOf(vm) == -1) {
@@ -308,7 +309,10 @@ public class AdminRootController {
uploadConfig.setUsermemory(Long.toString(Long.valueOf(uploadConfig.getUsermemory()) * 1024 * 1024));
uploadConfig.setFilesizeuser(Long.toString(Long.valueOf(uploadConfig.getFilesizeuser()) * 1024 * 1024));
uploadConfigService.setUpdateConfig(uploadConfig);
configService.setSourceype(config);
Confdata confdata = new Confdata();
confdata.setKey("config");
confdata.setJsondata(jsonObject.getJSONObject("config").toJSONString());
confdataService.updateConfdata(confdata);
sysConfigService.setstate(sysConfig);
if (!appClient.getIsuse().equals("on")) {
appClient.setIsuse("off");
@@ -3,7 +3,6 @@ package cn.hellohao.controller;
import cn.hellohao.auth.token.JWTUtil;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.AlbumServiceImpl;
import cn.hellohao.service.impl.UploadServicel;
import cn.hellohao.service.impl.deleImages;
import cn.hellohao.utils.GetIPS;
@@ -34,20 +33,19 @@ import java.util.UUID;
public class IndexController {
@Autowired private ImgService imgService;
@Autowired private SysConfigService sysConfigService;
@Autowired private ConfigService configService;
@Autowired private ConfdataService confdataService;
@Autowired private UploadConfigService uploadConfigService;
@Autowired private UploadServicel uploadServicel;
@Autowired private deleImages deleimages;
@Autowired private IRedisService iRedisService;
@Autowired private AlbumServiceImpl albumService;
@Autowired private AppClientService appClientService;
@RequestMapping(value = "/")
public String Welcome(Model model, HttpServletRequest httpServletRequest) {
model.addAttribute("name", "服务端程序");
model.addAttribute("version", "20221027");
model.addAttribute("name", "服务端程序(开源版)");
model.addAttribute("version", "20230320");
model.addAttribute("ip", GetIPS.getIpAddr(httpServletRequest));
model.addAttribute("links", "tbed.hellohao.cn");
model.addAttribute("links", "https://github.com/Hello-hao/tbed");
return "welcome";
}
@@ -55,21 +53,22 @@ public class IndexController {
@ResponseBody
public Msg webInfo() {
Msg msg = new Msg();
Config config = configService.getSourceype();
final Confdata confdata = confdataService.selectConfdata("config");
JSONObject cd = JSONObject.parseObject(confdata.getJsondata());
UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
SysConfig sysConfig = sysConfigService.getstate();
JSONObject jsonObject = new JSONObject();
AppClient appClient = appClientService.getAppClientData("app");
jsonObject.put("webname", config.getWebname());
jsonObject.put("websubtitle", config.getWebsubtitle());
jsonObject.put("keywords", config.getWebkeywords());
jsonObject.put("description", config.getWebms());
jsonObject.put("explain", config.getExplain());
jsonObject.put("favicon", config.getWebfavicons());
jsonObject.put("baidu", config.getBaidu());
jsonObject.put("links", config.getLinks());
jsonObject.put("aboutinfo", config.getAboutinfo());
jsonObject.put("logo", config.getLogo());
jsonObject.put("webname", cd.getString("webname"));
jsonObject.put("websubtitle", cd.getString("websubtitle"));
jsonObject.put("keywords", cd.getString("keywords"));
jsonObject.put("description", cd.getString("description"));
jsonObject.put("explain", cd.getString("explain"));
jsonObject.put("baidu", cd.getString("baidu"));
jsonObject.put("links", cd.getString("links"));
jsonObject.put("aboutinfo", cd.getString("aboutinfo"));
jsonObject.put("logo", cd.getString("logo"));
jsonObject.put("webfavicons", cd.getString("webfavicons"));
jsonObject.put("api", updateConfig.getApi());
jsonObject.put("register", sysConfig.getRegister());
jsonObject.put("isuse", appClient.getIsuse());
@@ -5,8 +5,10 @@ import cn.hellohao.auth.token.JWTUtil;
import cn.hellohao.config.SysName;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.utils.*;
import cn.hutool.captcha.ShearCaptcha;
import cn.hellohao.utils.Base64Encryption;
import cn.hellohao.utils.NewSendEmail;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.SetText;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
@@ -35,7 +37,7 @@ public class UserController {
@Autowired
private EmailConfigService emailConfigService;
@Autowired
private ConfigService configService;
private ConfdataService confdataService;
@Autowired
private UploadConfigService uploadConfigService;
@Autowired
@@ -45,21 +47,23 @@ public class UserController {
@PostMapping("/register")
@ResponseBody
public Msg Register(HttpSession httpSession, @RequestParam(value = "data", defaultValue = "") String data) {//Validated
public Msg Register(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data);
String username = jsonObj.getString("username");
String email = jsonObj.getString("email");
String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes());
String verifyCodeForRegister = jsonObj.getString("verifyCode");
ShearCaptcha redis_verifyCodeForRegister = (ShearCaptcha) httpSession.getAttribute("_hellohao_verifyCodeForRegister");//iRedisService.getValue(userIP+"_verifyCodeForRegister");
Object redis_verifyCodeForRegister = iRedisService.getValue("verifyCodeForRegister_"+httpServletRequest.getHeader("verifyCodeForRegister"));
if(!SetText.checkEmail(email)){
//邮箱格式不正确
msg.setCode("110403");
msg.setInfo("邮箱格式不正确");
return msg;
}
String regex = "^\\w+$";
if(username.length()>20 || !username.matches (regex)){
//用户名格式不正确
msg.setCode("110403");
msg.setInfo("用户名不得超过20位字符");
return msg;
@@ -73,7 +77,7 @@ public class UserController {
msg.setInfo("验证码不能为空。");
return msg;
}
if(redis_verifyCodeForRegister.verify(verifyCodeForRegister.toLowerCase())){
if((redis_verifyCodeForRegister.toString().toLowerCase()).compareTo((verifyCodeForRegister.toLowerCase()))==0){
User user = new User();
UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
EmailConfig emailConfig = emailConfigService.getemail();
@@ -106,18 +110,22 @@ public class UserController {
user.setEmail(email);
user.setUsername(username);
user.setPassword(password);
Config config = configService.getSourceype();
user.setToken(UUID.randomUUID().toString().replace("-", ""));
final Confdata confdata = confdataService.selectConfdata("config");
JSONObject jsonObject = JSONObject.parseObject(confdata.getJsondata());
Integer type = 0;
if(emailConfig.getUsing()==1){
user.setIsok(0);
//注册完发激活链接
Thread thread = new Thread() {
public void run() {
Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), uid, user.getEmail(),config);
Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), uid, user.getEmail(),jsonObject);
}
};
thread.start();
msg.setInfo("注册成功,请注意查收邮箱尽快激活账户");
}else{
//直接注册
user.setIsok(1);
msg.setInfo("注册成功,快去登陆吧");
}
@@ -131,13 +139,25 @@ public class UserController {
@PostMapping("/login")//new
@ResponseBody
public Msg login(HttpServletRequest request,HttpSession httpSession,@RequestParam(value = "data", defaultValue = "") String data) {
public Msg login(HttpServletRequest httpServletRequest,@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data);
String email = jsonObj.getString("email");
String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes());
String verifyCode = jsonObj.getString("verifyCode");
ShearCaptcha redis_VerifyCode = (ShearCaptcha)httpSession.getAttribute("_hellohao_verifyCode");
if(null == email || null == password || null == verifyCode){
msg.setCode("5000");
msg.setInfo("登录信息不正确");
return msg;
}
if(email.replace(" ","").equals("") || password.replace(" ","").equals("")
|| verifyCode.replace(" ","").equals("")){
msg.setCode("5000");
msg.setInfo("登录信息不正确");
return msg;
}
Object redis_VerifyCode = iRedisService.getValue("verifyCode_"+httpServletRequest.getHeader("verifyCode"));
if(null==redis_VerifyCode){
msg.setCode("4035");
msg.setInfo("验证码已失效,请重新弄获取。");
@@ -147,13 +167,13 @@ public class UserController {
msg.setInfo("验证码不能为空。");
return msg;
}
if(redis_VerifyCode.verify(verifyCode.toLowerCase())){
if((redis_VerifyCode.toString().toLowerCase()).compareTo((verifyCode.toLowerCase()))==0){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(email,password);
tokenOBJ.setRememberMe(true);
try {
subject.login(tokenOBJ);
SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时
SecurityUtils.getSubject().getSession().setTimeout(3600000);
JSONObject jsonObject = new JSONObject();
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user.getIsok()==0){
@@ -197,7 +217,7 @@ public class UserController {
}
}else{
msg.setCode("40034");
msg.setInfo("验证码不正确");//失效也要处理。
msg.setInfo("验证码不正确");
}
return msg;
}
@@ -205,7 +225,6 @@ public class UserController {
@RequestMapping(value = "/activation", method = RequestMethod.GET)
public String activation(Model model, HttpServletRequest request, HttpSession session, String activation, String username) {
Config config = configService.getSourceype();
Integer ret = 0;
User u2 = new User();
u2.setUid(activation);
@@ -236,15 +255,15 @@ public class UserController {
return msg;
}
@PostMapping("/retrievePass") //new
@PostMapping("/retrievePass")
@ResponseBody
public Msg retrievePass(HttpServletRequest request,HttpSession httpSession, @RequestParam(value = "data", defaultValue = "") String data) {
public Msg retrievePass(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg();
try {
JSONObject jsonObj = JSONObject.parseObject(data);
String email = jsonObj.getString("email");
String retrieveCode = jsonObj.getString("retrieveCode");
ShearCaptcha redis_verifyCodeForEmailRetrieve =(ShearCaptcha) httpSession.getAttribute("_hellohao_verifyCodeForEmailRetrieve");// iRedisService.getValue(userIP+"_verifyCodeForEmailRetrieve");
Object redis_verifyCodeForEmailRetrieve =iRedisService.getValue("verifyCodeForRetrieve_"+httpServletRequest.getHeader("verifyCodeForRetrieve"));
EmailConfig emailConfig = emailConfigService.getemail();
if(null==redis_verifyCodeForEmailRetrieve){
msg.setCode("4035");
@@ -255,12 +274,11 @@ public class UserController {
msg.setInfo("验证码不能为空。");
return msg;
}
if(!redis_verifyCodeForEmailRetrieve.verify(retrieveCode.toLowerCase())){
if((redis_verifyCodeForEmailRetrieve.toString().toLowerCase()).compareTo((retrieveCode.toLowerCase()))!=0){
msg.setCode("40034");
msg.setInfo("验证码不正确");
return msg;
}
Integer ret = userService.countmail(email);
if(ret>0){
if(emailConfig.getUsing()==1){
@@ -272,10 +290,11 @@ public class UserController {
msg.setInfo("当前用户已被冻结,禁止操作");
return msg;
}
Config config = configService.getSourceype();
final Confdata confdata = confdataService.selectConfdata("config");
JSONObject jsonObject = JSONObject.parseObject(confdata.getJsondata());
Thread thread = new Thread() {
public void run() {
Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),config);//SendEmail.sendEmailT(message, user.getUsername(), user.getUid(), user.getEmail(),emailConfig,config);
Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),jsonObject);
}
};
thread.start();
@@ -296,7 +315,7 @@ public class UserController {
return msg;
}
@RequestMapping(value = "/retrieve", method = RequestMethod.GET) //new
@RequestMapping(value = "/retrieve", method = RequestMethod.GET)
public String retrieve(Model model, String activation,String cip) {
Integer ret = 0;
try {
@@ -0,0 +1,11 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Confdata;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ConfdataMapper {
Confdata selectConfdata(@Param("key") String key);
Integer updateConfdata(Confdata confdata);
}
@@ -1,11 +0,0 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Config;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
@Mapper
public interface ConfigMapper {
Config getSourceype();
Integer setSourceype(Config config);
}
+5 -6
View File
@@ -1,12 +1,11 @@
package cn.hellohao.dao;
import java.util.List;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import cn.hellohao.pojo.Images;
import java.util.List;
@Mapper
public interface ImgMapper {
@@ -17,18 +16,18 @@ public interface ImgMapper {
Integer countimg(@Param("userid") Integer userid);
Integer deleimg(@Param("id") Integer id);
Integer deleimg(@Param("id") Long id);
Integer deleimgForImgUid(@Param("imguid") String imguid);
Images selectByPrimaryKey(@Param("id") Integer id);
Images selectByPrimaryKey(@Param("id") Long id);
Integer counts(@Param("userid") Integer userid);
Integer setImg(Images images);
Integer deleimgname(@Param("imgname") String imgname);
Integer deleall(@Param("id") Integer id);
Integer deleall(@Param("id") Long id);
List<Images> gettimeimg(@Param("time") String time);
@@ -0,0 +1,16 @@
package cn.hellohao.pojo;
import lombok.Data;
/**
* @author Hellohao
* @version 1.0
* @date 2023/3/2 10:21
*/
@Data
public class Confdata {
private String key;
private String jsondata;
}
+3 -196
View File
@@ -1,5 +1,8 @@
package cn.hellohao.pojo;
import lombok.Data;
@Data
public class Config {
private Integer id;
private Integer sourcekey;
@@ -23,201 +26,5 @@ public class Config {
private String logo;
private String aboutinfo;
public Config() {
}
public Config(Integer id, Integer sourcekey, Integer emails, String webname, String explain, String video, Integer backtype,
String links, String notice, String baidu, String domain, String background1, String background2, String sett,
String webms, String webkeywords, String webfavicons, Integer theme,String websubtitle,String logo,String aboutinfo) {
this.id = id;
this.sourcekey = sourcekey;
this.emails = emails;
this.webname = webname;
this.explain = explain;
this.video = video;
this.backtype = backtype;
this.links = links;
this.notice = notice;
this.baidu = baidu;
this.domain = domain;
this.background1 = background1;
this.background2 = background2;
this.sett = sett;
this.webms = webms;
this.webkeywords = webkeywords;
this.webfavicons = webfavicons;
this.theme = theme;
this.websubtitle = websubtitle;
this.logo = logo;
this.aboutinfo = aboutinfo;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getSourcekey() {
return sourcekey;
}
public void setSourcekey(Integer sourcekey) {
this.sourcekey = sourcekey;
}
public Integer getEmails() {
return emails;
}
public void setEmails(Integer emails) {
this.emails = emails;
}
public String getWebname() {
return webname;
}
public void setWebname(String webname) {
this.webname = webname;
}
public String getExplain() {
return explain;
}
public void setExplain(String explain) {
this.explain = explain;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public Integer getBacktype() {
return backtype;
}
public void setBacktype(Integer backtype) {
this.backtype = backtype;
}
public String getLinks() {
return links;
}
public void setLinks(String links) {
this.links = links;
}
public String getNotice() {
return notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
public String getBaidu() {
return baidu;
}
public void setBaidu(String baidu) {
this.baidu = baidu;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getBackground1() {
return background1;
}
public void setBackground1(String background1) {
this.background1 = background1;
}
public String getBackground2() {
return background2;
}
public void setBackground2(String background2) {
this.background2 = background2;
}
public String getSett() {
return sett;
}
public void setSett(String sett) {
this.sett = sett;
}
public String getWebms() {
return webms;
}
public void setWebms(String webms) {
this.webms = webms;
}
public String getWebkeywords() {
return webkeywords;
}
public void setWebkeywords(String webkeywords) {
this.webkeywords = webkeywords;
}
public String getWebfavicons() {
return webfavicons;
}
public void setWebfavicons(String webfavicons) {
this.webfavicons = webfavicons;
}
public Integer getTheme() {
return theme;
}
public void setTheme(Integer theme) {
this.theme = theme;
}
public String getWebsubtitle() {
return websubtitle;
}
public void setWebsubtitle(String websubtitle) {
this.websubtitle = websubtitle;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getAboutinfo() {
return aboutinfo;
}
public void setAboutinfo(String aboutinfo) {
this.aboutinfo = aboutinfo;
}
}
+4 -4
View File
@@ -4,7 +4,7 @@ public class Images {
// 默认的时间字符串格式
//id, imgname, imgurl, userid
private Integer id;
private Long id;
private String imgname;
private String imgurl;
private Integer userid;
@@ -52,7 +52,7 @@ public class Images {
this.imguid = imguid;
}
public Images(Integer id, String imgname, String imgurl, Integer userid, String sizes, String abnormal, Integer source,
public Images(Long id, String imgname, String imgurl, Integer userid, String sizes, String abnormal, Integer source,
Integer imgtype, String updatetime, String username, Integer storageType, String starttime, String stoptime,
String explains, String md5key, String notes, String useridlist, String imguid, String albumtitle,
String password, Integer selecttype,Long countNum,Integer monthNum,String yyyy,
@@ -93,11 +93,11 @@ public class Images {
}
public Integer getId() {
public Long getId() {
return id;
}
public void setId(Integer id) {
public void setId(Long id) {
this.id = id;
}
+5 -81
View File
@@ -1,94 +1,18 @@
package cn.hellohao.pojo;
import lombok.Data;
@Data
public class Keys {
private Integer id;
private String AccessKey;
private String AccessSecret;
private String Endpoint;
private String Region;
private String Bucketname;
private String RequestAddress;
private Integer storageType;
private String keyname;
private String RootPath;//存入的目录
public Keys() {
super();
}
public Keys(Integer id, String accessKey, String accessSecret, String endpoint, String bucketname,
String requestAddress, Integer storageType,String keyname) {
super();
this.id = id;
this.AccessKey = accessKey;
this.AccessSecret = accessSecret;
this.Endpoint = endpoint;
this.Bucketname = bucketname;
this.RequestAddress = requestAddress;
this.storageType = storageType;
this.keyname = keyname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccessKey() {
return AccessKey;
}
public void setAccessKey(String accessKey) {
AccessKey = accessKey;
}
public String getAccessSecret() {
return AccessSecret;
}
public void setAccessSecret(String accessSecret) {
AccessSecret = accessSecret;
}
public String getEndpoint() {
return Endpoint;
}
public void setEndpoint(String endpoint) {
Endpoint = endpoint;
}
public String getBucketname() {
return Bucketname;
}
public void setBucketname(String bucketname) {
Bucketname = bucketname;
}
public String getRequestAddress() {
return RequestAddress;
}
public void setRequestAddress(String requestAddress) {
RequestAddress = requestAddress;
}
public Integer getStorageType() {
return storageType;
}
public void setStorageType(Integer storageType) {
this.storageType = storageType;
}
public String getKeyname() {
return keyname;
}
public void setKeyname(String keyname) {
this.keyname = keyname;
}
}
@@ -32,9 +32,9 @@ public class FirstJob {
@Autowired
private USSImageupload ussImageupload;
@Autowired
private UFileImageupload uFileImageupload;
private S3Imageupload s3Imageupload;
@Autowired
private FTPImageupload ftpImageupload;
private FtpServiceImpl ftpService;
@Autowired
ImgTempService imgTempService;
@Autowired
@@ -75,9 +75,9 @@ public class FirstJob {
}else if(keys.getStorageType()==6){
firstJob.cosImageupload.delCOS(keys.getId(),images);
}else if(keys.getStorageType()==7){
firstJob.ftpImageupload.delFTP(keys.getId(), images);
firstJob.ftpService.delFTP(keys.getId(), images);
}else if(keys.getStorageType()==8){
firstJob.uFileImageupload.delUFile(keys.getId(), images);
firstJob.s3Imageupload.deleS3(keys.getId(), images);
}else{
System.err.println("未获取到对象存储参数,上传失败。");
}
@@ -0,0 +1,10 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Confdata;
import org.springframework.stereotype.Service;
@Service
public interface ConfdataService {
Confdata selectConfdata(String key);
Integer updateConfdata(Confdata confdata);
}
@@ -1,10 +0,0 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Config;
import org.springframework.stereotype.Service;
@Service
public interface ConfigService {
Config getSourceype();
Integer setSourceype(Config config);
}
@@ -1,27 +1,25 @@
package cn.hellohao.service;
import java.util.List;
import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Param;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface ImgService {
List<Images> selectimg(Images images);
Integer insertImgData(Images images);
Integer deleimg(Integer id);
Integer deleimg(Long id);
Integer deleimgForImgUid(String imguid);
Integer countimg(Integer userid);
Images selectByPrimaryKey(Integer id);
Images selectByPrimaryKey(Long id);
Integer counts(Integer userid);
@@ -29,7 +27,7 @@ public interface ImgService {
Integer deleimgname(String imgname);
Integer deleall(Integer id);
Integer deleall(Long id);
List<Images> gettimeimg(String time);
@@ -1,7 +1,6 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.AlbumMapper;
import cn.hellohao.dao.ConfigMapper;
import cn.hellohao.dao.ImgAndAlbumMapper;
import cn.hellohao.dao.ImgMapper;
import cn.hellohao.exception.CodeException;
@@ -25,7 +24,6 @@ import java.util.List;
public class AlbumServiceImpl implements AlbumService {
@Autowired AlbumMapper albumMapper;
@Autowired ImgAndAlbumMapper andAlbumMapper;
@Autowired ConfigMapper configMapper;
@Autowired ImgMapper imgMapper;
@Override
@@ -3,12 +3,8 @@ package cn.hellohao.service.impl;
import cn.hellohao.dao.*;
import cn.hellohao.pojo.*;
import cn.hellohao.service.ImgTempService;
import cn.hellohao.service.SysConfigService;
import cn.hellohao.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -28,20 +24,21 @@ import java.util.*;
@Service
public class ClientService {
@Autowired private SysConfigService sysConfigService;
@Autowired private UserMapper userMapper;
@Autowired private KeysMapper keysMapper;
@Autowired private UploadConfigMapper uploadConfigMapper;
@Autowired private ImgMapper imgMapper;
@Autowired private ImgreviewMapper imgreviewMapper;
@Autowired private ImgTempService imgTempService;
@Autowired private KeysServiceImpl keysService;
@Autowired private GetSource getSource;
@Autowired private ImgViolationJudgeServiceImpl imgViolationJudgeService;
public Msg uploadImg(
HttpServletRequest request, MultipartFile multipartFile, String email, String pass,Integer setday) {
Msg msg = new Msg();
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String imageFileName = "未命名图像";
Integer sourceKeyId = 0;
FileInputStream fis = null;
String md5key = null;
@@ -53,6 +50,7 @@ public class ClientService {
msg.setInfo("管理员关闭了API接口");
return msg;
}
imageFileName = multipartFile.getOriginalFilename();
File file = SetFiles.changeFile_new(multipartFile);
User u2 = new User();
if (!file.exists() || email == null || pass == null) {
@@ -115,19 +113,6 @@ public class ClientService {
}
}
}
// if (Integer.valueOf(sysConfigService.getstate().getCheckduplicate()) == 1) {
// Images imaOBJ = new Images();
// imaOBJ.setMd5key(md5key);
// imaOBJ.setUserid(u.getId());
// if (imgMapper.md5Count(imaOBJ) > 0) {
// List<Images> images = imgMapper.selectImgUrlByMD5(md5key);
// jsonObject.put("url", images.get(0).getImgurl());
// jsonObject.put("name", file.getName());
// jsonObject.put("size", images.get(0).getSizes());
// msg.setData(jsonObject);
// return msg;
// }
// }
Images imgObj = new Images();
String imgnameEd = null;
Map<Map<String, String>, File> map = new HashMap<>();
@@ -145,6 +130,10 @@ public class ClientService {
imgObj.setImgurl(key.getRequestAddress() + "/" + imgnameEd);
}
imgObj.setSizes(Long.toString(file.length()));
}else{
msg.setInfo("未获取到指定图像:110503");
msg.setCode("110503");
return msg;
}
imgObj.setUpdatetime(df.format(new Date()));
imgObj.setSource(key.getId());
@@ -162,6 +151,7 @@ public class ClientService {
imgObj.setMd5key(md5key);
imgObj.setImguid(imguid);
imgObj.setFormat(fileMiME.getData().toString());
imgObj.setIdname(imageFileName);
Integer insertRet = imgMapper.insertImgData(imgObj);
if (insertRet == 0) {
Images imaOBJ = new Images();
@@ -170,16 +160,6 @@ public class ClientService {
List<Images> images = imgMapper.selectImgUrlByMD5(md5key);
if (images.size() > 0) {
jsonObject.put("url", images.get(0).getImgurl());
// Keys imgFromKey = keysService.selectKeys(images.get(0).getSource());
// if (imgFromKey.getStorageType().equals(5)) {
// jsonObject.put(
// "url",
// imgFromKey.getRequestAddress()
// + "/ota/"
// + images.get(0).getImgname());
// } else {
// jsonObject.put("url", images.get(0).getImgurl());
// }
jsonObject.put("name", file.getName());
jsonObject.put("size", images.get(0).getSizes());
msg.setData(jsonObject);
@@ -191,21 +171,16 @@ public class ClientService {
}
}
long stime = System.currentTimeMillis();
Map<ReturnImage, Integer> m = null;
ReturnImage returnImage =
GetSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
if (returnImage.getCode().equals("200")) {
long etime = System.currentTimeMillis();
Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms");
jsonObject.put("url", imgObj.getImgurl());
jsonObject.put("name", imgObj.getImgname());
jsonObject.put("size", imgObj.getSizes());
new Thread(
() -> {
LegalImageCheck(imgObj);
})
.start();
imgViolationJudgeService.LegalImageCheck(imgObj,key);
} else {
imgMapper.deleimgForImgUid(imgObj.getImguid());
msg.setCode("5001");
msg.setInfo("上传服务内部错误");
return msg;
@@ -273,67 +248,4 @@ public class ClientService {
return msg;
}
// 图片鉴黄
private synchronized void LegalImageCheck(Images images) {
Imgreview imgreview = null;
try {
imgreview = imgreviewMapper.selectByusing(1);
} catch (Exception e) {
Print.warning("获取鉴别程序的时候发生错误");
e.printStackTrace();
}
if(imgreview==null){
System.out.println("没有找到可用的图像鉴别进程");
}else{
LegalImageCheckForBaiDu(imgreview, images);
}
}
private void LegalImageCheckForBaiDu(Imgreview imgreview, Images images) {
if (imgreview.getUsing() == 1) {
try {
AipContentCensor client =
new AipContentCensor(
imgreview.getAppId(),
imgreview.getApiKey(),
imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(5000);
client.setSocketTimeoutInMillis(30000);
org.json.JSONObject res = client.antiPorn(images.getImgurl());
res = client.imageCensorUserDefined(images.getImgurl(), EImgType.URL, null);
com.alibaba.fastjson.JSONArray jsonArray =
JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
JSONObject jsonObject = (JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if (conclusionType != null) {
if (conclusionType == 2) {
for (Object datum : data) {
JSONObject imgdata = (JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
Images img = new Images();
img.setImgname(images.getImgname());
img.setViolation("1[1]");
imgMapper.setImg(img);
Imgreview imgv = new Imgreview();
imgv.setId(1);
Integer count = imgreview.getCount();
System.out.println("违法图片总数:" + count);
imgv.setCount(count + 1);
imgreviewMapper.updateByPrimaryKeySelective(imgv);
System.err.println("存在非法图片,进行处理操作");
}
}
}
}
}
} catch (Exception e) {
System.out.println("图像鉴黄线程执行过程中出现异常");
e.printStackTrace();
}
}
}
}
@@ -0,0 +1,23 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ConfdataMapper;
import cn.hellohao.pojo.Confdata;
import cn.hellohao.service.ConfdataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfdataServiceImpl implements ConfdataService {
@Autowired
private ConfdataMapper confdataMapper;
@Override
public Confdata selectConfdata(String key) {
return confdataMapper.selectConfdata(key);
}
@Override
public Integer updateConfdata(Confdata confdata) {
return confdataMapper.updateConfdata(confdata);
}
}
@@ -1,24 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ConfigMapper;
import cn.hellohao.pojo.Config;
import cn.hellohao.pojo.Images;
import cn.hellohao.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfigServiceImpl implements ConfigService {
@Autowired
private ConfigMapper configMapper;
@Override
public Config getSourceype() {
return configMapper.getSourceype();
}
@Override
public Integer setSourceype(Config config) {
return configMapper.setSourceype(config);
}
}
@@ -1,132 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.utils.FTPUtils;
import cn.hellohao.utils.Print;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
@Service
public class FTPImageupload {
static Keys key;
public ReturnImage ImageuploadFTP(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
boolean flag = ftps.open();
File file = null;
ftps.mkDir(File.separator + username);
try {
for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
String userkey = username + "/" + ShortUIDName + "." + prefix;
if (flag) {
boolean isUpload = ftps.upload(file, "/" + userkey, "");
if (isUpload) {
} else {
returnImage.setCode("400");
}
} else {
returnImage.setCode("400");
}
Print.Normal("要上传的文件路径:/" + userkey);
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
}
return returnImage;
}
public static Integer Initialize(Keys k) {
int ret = -1;
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getRequestAddress())) {
return -1;
}
FTPClient ftp = new FTPClient();
ftp.setConnectTimeout(0);
int flag = k.getEndpoint().indexOf(":");
if (flag > 0) {
String[] host = k.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if (!ftp.isConnected()) {
ftp.connect(h, p);
}
ftp.login(k.getAccessKey(), k.getAccessSecret());
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("FTP Object Is null");
ftp.disconnect();
return -1;
}
ret = 1;
key = k;
} catch (IOException e) {
System.out.println("FTP Object Is null");
return -1;
}
}
return ret;
}
public static void copyFile(String p1, String p2) {
String a = p1;
try {
File afile = new File(a);
File bfile = new File(p2); // 定义一个复制后的文件路径
bfile.createNewFile();
FileInputStream c = new FileInputStream(afile);
FileOutputStream d = new FileOutputStream(bfile);
byte[] date = new byte[512];
int i = 0;
while ((i = c.read(date)) > 0) {
d.write(date);
}
c.close();
d.close();
System.out.println("文件复制成功");
} catch (IOException e) {
e.printStackTrace();
}
}
public Boolean delFTP(Integer keyID, Images images) {
boolean b = true;
try {
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
ftps.open();
b = ftps.deleteFile(images.getImgname());
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -0,0 +1,107 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class FtpServiceImpl {
private Keys key;
public static int Initialize(Keys k) {
int ret = -1;
try{
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getRequestAddress())){
return -1;
}
Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8");
String[] hostArr = k.getEndpoint().split("\\:");
String host = hostArr[0];
Integer port = Integer.parseInt(hostArr[1]);
Ftp ftp = new Ftp(host, port, k.getAccessKey(), k.getAccessSecret(), charset);
ftp.getClient().type(FTP.BINARY_FILE_TYPE);
ftp.setMode(FtpMode.Passive);
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public ReturnImage FtpUploadFile(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
Ftp ftp = null;
try {
if (null == key) {
System.out.println("FTP = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8");
String[] hostArr = key.getEndpoint().split("\\:");
String host = hostArr[0];
Integer port = Integer.parseInt(hostArr[1]);
ftp = new Ftp(host, port, key.getAccessKey(), key.getAccessSecret(), charset);
ftp.getClient().type(FTP.BINARY_FILE_TYPE);
ftp.setMode(FtpMode.Passive);
} catch (Exception e) {
e.printStackTrace();
System.out.println("FTP = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
File file = null;
try {
for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
boolean isUpload = ftp.upload(
"/" + username,
ShortUIDName + "." + prefix,
file);
if (!isUpload) {
returnImage.setCode("400");
}
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
}
return returnImage;
}
public Boolean delFTP(Integer keyID, Images images) {
boolean b = true;
Ftp ftp = null;
try {
Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8");
String[] hostArr = key.getEndpoint().split("\\:");
String host = hostArr[0];
Integer port = Integer.parseInt(hostArr[1]);
ftp = new Ftp(host, port, key.getAccessKey(), key.getAccessSecret(), charset);
b = ftp.delFile(images.getImgname());
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -26,7 +26,7 @@ public class ImgServiceImpl implements ImgService {
}
@Override
public Integer deleimg(Integer id) {
public Integer deleimg(Long id) {
// TODO Auto-generated method stub
return imgMapper.deleimg(id);
}
@@ -36,7 +36,7 @@ public class ImgServiceImpl implements ImgService {
return imgMapper.deleimgForImgUid(imguid);
}
public Images selectByPrimaryKey(Integer id) {
public Images selectByPrimaryKey(Long id) {
return imgMapper.selectByPrimaryKey(id);
}
@@ -63,7 +63,7 @@ public class ImgServiceImpl implements ImgService {
}
@Override
public Integer deleall(Integer id) {
public Integer deleall(Long id) {
return imgMapper.deleall(id);
}
@@ -0,0 +1,116 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ImgMapper;
import cn.hellohao.dao.ImgreviewMapper;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Imgreview;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.utils.FirstRun;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ImgViolationJudgeServiceImpl {
private static Logger logger = LoggerFactory.getLogger(FirstRun.class);
@Autowired
ImgreviewServiceImpl imgreviewService;
@Autowired ImgMapper imgMapper;
@Autowired deleImages deleimages;
@Autowired private ImgreviewMapper imgreviewMapper;
//synchronized
@Async("taskExecutor")
public void LegalImageCheck(Images images, Keys keys) {
Imgreview imgreview = null;
try {
imgreview = imgreviewService.selectByusing(1);
} catch (Exception e) {
logger.error("获取鉴别程序的时候发生错误");
e.printStackTrace();
}
// 判断哪个鉴别平台
if (null != imgreview) {
LegalImageCheckForBaiDu(imgreview, images, keys);
}
}
private void LegalImageCheckForBaiDu(Imgreview imgreview, Images images, Keys keys) {
// Imgreview imgreview = imgreviewService.selectByPrimaryKey(1);
if (imgreview.getUsing() == 1) {
logger.info("非法图像鉴别进程启动-BaiDu");
try {
AipContentCensor client =
new AipContentCensor(
imgreview.getAppId(),
imgreview.getApiKey(),
imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(5000);
client.setSocketTimeoutInMillis(30000);
// res = client.antiPorn(images.getImgurl());
org.json.JSONObject res = client.imageCensorUserDefined(images.getImgurl(), EImgType.URL, null);
logger.info("返回的鉴黄json:" + res.toString());
com.alibaba.fastjson.JSONArray jsonArray =
JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
JSONObject jsonObject =
(JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if (conclusionType != null) {
if (conclusionType == 2) {
// 1:合规,2:不合规,3:疑似,4:审核失败
for (Object datum : data) {
JSONObject imgdata =
(JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
logger.info("存在非法图片,进行处理操作");
// type参数
// 0:百度官方违禁图库、1:色情识别、2:暴恐识别、3:恶心图识别、4:广告检测、5:政治敏感识别、6:图像质量检测、7:用户图像黑名单、8:用户图像白名单、10:用户头像审核、11:百度官方违禁词库、12:图文审核、13:自定义文本黑名单、14:自定义文本白名单、15:EasyDL自定义模型、16:敏感旗帜标志识别、21:不良场景识别、24:直播场景审核
// 存在非法图片,进行处理操作
Images img = new Images();
img.setImgname(images.getImgname());
img.setViolation("1[1]"); // 数字是鉴别平台的主键ID,括号是非法的类型,参考上面的注释
imgMapper.setImg(img);
// 计入总数
Imgreview imgv = new Imgreview();
imgv.setId(1);
Integer count = imgreview.getCount();
imgv.setCount(count + 1);
imgreviewMapper.updateByPrimaryKeySelective(imgv);
Images imgObj =
imgMapper.selectImgUrlByImgUID(images.getImguid());
Msg dele = deleimages.dele2(Long.toString(imgObj.getId()));
List<Long> ids = (List<Long>) dele.getData();
if (!ids.contains(imgObj.getId())) {
logger.error("检测到违规图像,但是数据库删除失败");
}
}
}
}
}
}
} catch (Exception e) {
logger.error("图像鉴黄线程执行过程中出现异常");
e.printStackTrace();
}
}
}
}
@@ -4,6 +4,8 @@ import cn.hellohao.auth.filter.SubjectFilter;
import cn.hellohao.dao.KeysMapper;
import cn.hellohao.pojo.Keys;
import cn.hellohao.utils.Print;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
@@ -23,6 +25,7 @@ import java.util.List;
@Order(2)
public class InitializationStorage implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(InitializationStorage.class);
@Value("${CROS_ALLOWED_ORIGINS}")
private String allowedOrigins;
@@ -30,7 +33,7 @@ public class InitializationStorage implements CommandLineRunner {
private KeysMapper keysMapper;
@Override
public void run(String... args) throws Exception {
public void run(String... args) {
SubjectFilter.WEBHOST = allowedOrigins;
String name = ManagementFactory.getRuntimeMXBean().getName();
String pid = name.split("@")[0];
@@ -41,21 +44,20 @@ public class InitializationStorage implements CommandLineRunner {
List<Keys> keylist = keysMapper.getKeys();
for (Keys key : keylist) {
if(key.getStorageType()!=0 && key.getStorageType()!=null){
int ret =0;
if(key.getStorageType()==1){
ret =NOSImageupload.Initialize(key);
NOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){
ret =OSSImageupload.Initialize(key);
OSSImageupload.Initialize(key);
}else if(key.getStorageType()==3){
ret = USSImageupload.Initialize(key);
USSImageupload.Initialize(key);
}else if(key.getStorageType()==4){
ret = KODOImageupload.Initialize(key);
KODOImageupload.Initialize(key);
}else if(key.getStorageType()==6){
ret = COSImageupload.Initialize(key);
COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){
ret = FTPImageupload.Initialize(key);
FtpServiceImpl.Initialize(key);
}else if(key.getStorageType()==8){
ret = UFileImageupload.Initialize(key);
S3Imageupload.Initialize(key);
}
}
}
@@ -16,7 +16,6 @@ public class KeysServiceImpl implements KeysService {
@Autowired
private KeysMapper keysMapper;
@Autowired
private NOSImageupload nOSImageupload;
@Autowired
@@ -28,9 +27,9 @@ public class KeysServiceImpl implements KeysService {
@Autowired
private COSImageupload cosImageupload;
@Autowired
private FTPImageupload ftpImageupload;
private FtpServiceImpl ftpService;
@Autowired
private UFileImageupload uFileImageupload;
private S3Imageupload s3Imageupload;
@Override
@@ -65,9 +64,9 @@ public class KeysServiceImpl implements KeysService {
}else if(key.getStorageType()==6){
ret = cosImageupload.Initialize(key);
}else if(key.getStorageType()==7){
ret = ftpImageupload.Initialize(key);
ret = ftpService.Initialize(key);
}else if(key.getStorageType()==8){
ret = uFileImageupload.Initialize(key);
ret = s3Imageupload.Initialize(key);
}else{
Print.Normal("为获取到存储参数,或者使用存储源是本地的。");
}
@@ -0,0 +1,167 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
import java.util.Map;
/**
* @author Hellohao
* @version 1.0
* @date 2023/3/15 14:04
*/
@Service
public class S3Imageupload {
private static Logger logger = LoggerFactory.getLogger(S3Imageupload.class);
static AmazonS3 AS3;
static Keys KEY;
public ReturnImage ImageuploadS3(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
try {
if (null == AS3 || null == AS3) {
logger.error("S3 = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
return returnImage;
}
File file = null;
try {
for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
AS3.putObject(
new PutObjectRequest(
KEY.getBucketname(),
username + "/" + ShortUIDName + "." + prefix,
file));
// S3Object object = s3.getObject( new GetObjectRequest( key.getBucketname(),
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
}
return returnImage;
}
public static Integer Initialize(Keys k) {
int ret = -1;
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getRootPath())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getBucketname())
|| StringUtils.isBlank(k.getRequestAddress())) {
return -1;
}
try {
String regionStr = k.getRegion() == null ? "" : k.getRegion();
ClientConfiguration config = new ClientConfiguration();
config.setMaxConnections(500);
config.setConnectionTimeout(30);
// cn-north-1 us-east-1
BasicAWSCredentials credentials =
new BasicAWSCredentials(k.getAccessKey(), k.getAccessSecret());
AmazonS3 s3 =
AmazonS3ClientBuilder.standard()
.withClientConfiguration(config)
.withPathStyleAccessEnabled(false)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(
k.getEndpoint(), regionStr))
.build();
ObjectListing objectListing = s3.listObjects(k.getBucketname());
ret = 1;
AS3 = s3;
KEY = k;
} catch (Exception e) {
logger.warn("S3 Object " + k.getKeyname() + " Is null");
ret = -1;
}
if(ret==-1){
ret = Initialize_Tow(k);
if(ret>-1){
//OK
}
}
return ret;
}
public static Integer Initialize_Tow(Keys k) {
int ret = -1;
try {
ClientConfiguration config = new ClientConfiguration();
AwsClientBuilder.EndpointConfiguration endpointConfig =
new AwsClientBuilder.EndpointConfiguration(k.getEndpoint(), k.getRegion());//cn-north-1
AWSCredentials awsCredentials = new BasicAWSCredentials(k.getAccessKey(),k.getAccessSecret());
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
AmazonS3 s3 = AmazonS3Client.builder()
.withEndpointConfiguration(endpointConfig)
.withClientConfiguration(config)
.withCredentials(awsCredentialsProvider)
.disableChunkedEncoding()
.withPathStyleAccessEnabled(true)
.build();
List<Bucket> buckets = s3.listBuckets();
boolean b = false;
for (Bucket bucket : buckets) {
if(k.getBucketname().equals(bucket.getName())){
b = true;
}
}
if(b==false){
throw new NullPointerException();
}
ret=1;
AS3 = s3;
KEY = k;
} catch (Exception e) {
ret = -1;
}
return ret;
}
public boolean deleS3(Integer keyID, Images images) {
boolean b = true;
try {
DeleteObjectRequest deleteObjectRequest =
new DeleteObjectRequest(KEY.getBucketname(), images.getImgname());
AS3.deleteObject(deleteObjectRequest);
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -15,7 +15,7 @@ import java.util.List;
import java.util.Map;
@Service
public class UFileImageupload {
public class UFileImageupload1 {
static UpYun uFile;
static Keys key;
@@ -4,13 +4,12 @@ import cn.hellohao.dao.*;
import cn.hellohao.pojo.*;
import cn.hellohao.service.ImgTempService;
import cn.hellohao.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -28,13 +27,16 @@ import java.util.*;
*/
@Service
public class UploadServicel {
private static Logger logger = LoggerFactory.getLogger(UploadServicel.class);
@Autowired private UploadConfigMapper uploadConfigMapper;
@Autowired private KeysMapper keysMapper;
@Autowired private ImgMapper imgMapper;
@Autowired private UserMapper userMapper;
@Autowired private ImgreviewMapper imgreviewMapper;
@Autowired private ImgTempService imgTempService;
@Autowired private KeysServiceImpl keysService;
@Autowired private GetSource getSource;
@Autowired deleImages deleimages;
@Autowired ImgViolationJudgeServiceImpl imgViolationJudgeService;
public Msg uploadForLoc(
HttpServletRequest request,
@@ -44,6 +46,7 @@ public class UploadServicel {
Msg msg = new Msg();
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String imageFileName = "未命名图像";
JSONObject jsonObject = new JSONObject();
UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig();
String userip = GetIPS.getIpAddr(request);
@@ -57,8 +60,10 @@ public class UploadServicel {
FileInputStream fis = null;
File file = null;
if (imgUrl == null) {
imageFileName = multipartFile.getOriginalFilename();
file = SetFiles.changeFile_new(multipartFile);
} else {
imageFileName = "URL转存图像";
Msg imgData = uploadForURL(request, imgUrl);
if (imgData.getCode().equals("200")) {
file = new File((String) imgData.getData());
@@ -102,19 +107,6 @@ public class UploadServicel {
if (md5key == null || md5key.equals("")) {
md5key = UUID.randomUUID().toString().replace("-", "");
}
// if(Integer.valueOf(sysConfigService.getstate().getCheckduplicate())==1){
// Images imaOBJ = new Images();
// imaOBJ.setMd5key(md5key);
// imaOBJ.setUserid(u==null?0:u.getId());
// if(imgMapper.md5Count(imaOBJ)>0){
// List<Images> images = imgMapper.selectImgUrlByMD5(md5key);
// jsonObject.put("url", images.get(0).getImgurl());
// jsonObject.put("name",file.getName());
// jsonObject.put("imguid",images.get(0).getImguid());
// msg.setData(jsonObject);
// return msg;
// }
// }
String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
// 判断黑名单
if (uploadConfig.getBlacklist() != null) {
@@ -146,6 +138,10 @@ public class UploadServicel {
imgObj.setImgurl(key.getRequestAddress() + "/" + imgnameEd);
}
imgObj.setSizes(Long.toString(file.length()));
}else{
msg.setInfo("未获取到指定图像:110503");
msg.setCode("110503");
return msg;
}
imgObj.setUpdatetime(df.format(new Date()));
imgObj.setSource(key.getId());
@@ -163,6 +159,7 @@ public class UploadServicel {
imgObj.setMd5key(md5key);
imgObj.setImguid(imguid);
imgObj.setFormat(fileMiME.getData().toString());
imgObj.setIdname(imageFileName);
Integer insertRet = imgMapper.insertImgData(imgObj);
if (insertRet == 0) {
Images imaOBJ = new Images();
@@ -192,20 +189,21 @@ public class UploadServicel {
}
}
long stime = System.currentTimeMillis();
ReturnImage returnImage =
GetSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
if (returnImage.getCode().equals("200")) {
long etime = System.currentTimeMillis();
Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms");
jsonObject.put("url", imgObj.getImgurl());
jsonObject.put("name", imgObj.getImgname());
jsonObject.put("imguid", imgObj.getImguid());
new Thread(
() -> {
LegalImageCheck(imgObj);
})
.start();
imgViolationJudgeService.LegalImageCheck(imgObj,key);
// new Thread(
// () -> {
// LegalImageCheck(imgObj);
// })
// .start();
} else {
imgMapper.deleimgForImgUid(imgObj.getImguid());
msg.setCode("5001");
msg.setInfo("上传服务内部错误");
return msg;
@@ -314,70 +312,6 @@ public class UploadServicel {
return msg;
}
private synchronized void LegalImageCheck(Images images) {
System.out.println("非法图像鉴别进程启动");
Imgreview imgreview = null;
try {
imgreview = imgreviewMapper.selectByusing(1);
} catch (Exception e) {
Print.warning("获取鉴别程序的时候发生错误");
e.printStackTrace();
}
if (null != imgreview) {
LegalImageCheckForBaiDu(imgreview, images);
}
}
private void LegalImageCheckForBaiDu(Imgreview imgreview, Images images) {
System.out.println("非法图像鉴别进程启动-BaiDu");
if (imgreview.getUsing() == 1) {
try {
AipContentCensor client =
new AipContentCensor(
imgreview.getAppId(),
imgreview.getApiKey(),
imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(5000);
client.setSocketTimeoutInMillis(30000);
org.json.JSONObject res = client.antiPorn(images.getImgurl());
res = client.imageCensorUserDefined(images.getImgurl(), EImgType.URL, null);
System.err.println("返回的鉴黄json:" + res.toString());
com.alibaba.fastjson.JSONArray jsonArray =
JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
com.alibaba.fastjson.JSONObject jsonObject =
(com.alibaba.fastjson.JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if (conclusionType != null) {
if (conclusionType == 2) {
for (Object datum : data) {
com.alibaba.fastjson.JSONObject imgdata =
(com.alibaba.fastjson.JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
Images img = new Images();
img.setImgname(images.getImgname());
img.setViolation("1[1]");
imgMapper.setImg(img);
Imgreview imgv = new Imgreview();
imgv.setId(1);
Integer count = imgreview.getCount();
System.out.println("违法图片总数:" + count);
imgv.setCount(count + 1);
imgreviewMapper.updateByPrimaryKeySelective(imgv);
System.err.println("存在非法图片,进行处理操作");
}
}
}
}
}
} catch (Exception e) {
System.out.println("图像鉴黄线程执行过程中出现异常");
e.printStackTrace();
}
}
}
// 计算时间
public static String plusDay(int setday) {
@@ -24,19 +24,19 @@ public class deleImages {
@Autowired private COSImageupload cosImageupload;
@Autowired private KODOImageupload kodoImageupload;
@Autowired private USSImageupload ussImageupload;
@Autowired private UFileImageupload uFileImageupload;
@Autowired private FTPImageupload ftpImageupload;
@Autowired private S3Imageupload s3Imageupload;
@Autowired private FtpServiceImpl ftpService;
@Autowired private ImgAndAlbumService imgAndAlbumService;
@Autowired private ImgTempService imgTempService;
@Autowired private ImgService imgService;
@Autowired private KeysServiceImpl keysService;
@Autowired private IRedisService iRedisService;
public Msg dele(String uuid, Integer... imgIds) {
public Msg dele(String uuid, Long... imgIds) {
Msg msg = new Msg();
MyProgress myProgress = new MyProgress();
myProgress.InitializeDelImg();
List<Integer> ids = new ArrayList<>();
List<Long> ids = new ArrayList<>();
int successCount = 0;
List<String> errorIds = new ArrayList<>();
for (int i = 0; i < imgIds.length; i++) {
@@ -58,26 +58,26 @@ public class deleImages {
} else if (key.getStorageType() == 6) {
isDele = cosImageupload.delCOS(key.getId(), image);
} else if (key.getStorageType() == 7) {
isDele = ftpImageupload.delFTP(key.getId(), image);
isDele = ftpService.delFTP(key.getId(), image);
} else if (key.getStorageType() == 8) {
isDele = uFileImageupload.delUFile(key.getId(), image);
isDele = s3Imageupload.deleS3(key.getId(), image);
} else {
System.err.println("未获取到对象存储参数,删除失败。");
}
if (isDele) {
try {
imgAndAlbumService.deleteImgAndAlbum(image.getImgurl());
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
ids.add(image.getId());
successCount++;
System.out.println("删除成功加一个" + image.getId());
} catch (Exception e) {
e.printStackTrace();
System.err.println(image.getImgname() + ":图片数据库记录时发生错误");
errorIds.add(image.getImgurl());
}
// if (isDele) {
try {
imgAndAlbumService.deleteImgAndAlbum(image.getImgurl());
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
ids.add(image.getId());
successCount++;
System.out.println("删除成功加一个" + image.getId());
} catch (Exception e) {
e.printStackTrace();
System.err.println(image.getImgname() + ":图片数据库记录时发生错误");
errorIds.add(image.getImgurl());
}
// }
if(uuid!=null){
myProgress.setDelSuccessCount(successCount);
myProgress.setDelSuccessImgList(ids);
@@ -89,11 +89,21 @@ public class deleImages {
}
iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L);
}
// if (null != httpSession) {
// httpSession.setAttribute("myProgressForDel", myProgress);
// }
} catch (Exception e) {
System.err.println("删除的时候发生了一些异常");
ids.add(imgIds[i]);
successCount++;
if(uuid!=null){
myProgress.setDelSuccessCount(successCount);
myProgress.setDelSuccessImgList(ids);
myProgress.setDelErrorImgListt(errorIds);
if (imgIds.length == (i + 1)) {
myProgress.setDelOCT(1);
} else {
myProgress.setDelOCT(0);
}
iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L);
}
e.printStackTrace();
}
}
@@ -101,9 +111,50 @@ public class deleImages {
return msg;
}
public static void main(String[] args) {
MyProgress myProgress = new MyProgress();
myProgress.InitializeDelImg();
System.out.println(JSONObject.toJSONString(myProgress));
public Msg dele2(String... imgIds) {
Msg msg = new Msg();
List<Long> ids = new ArrayList<>();
for (int i = 0; i < imgIds.length; i++) {
try {
Images image = imgService.selectByPrimaryKey(Long.valueOf(imgIds[i]));
Keys key = keysService.selectKeys(image.getSource());
if (key.getStorageType() == 1) {
nosImageupload.delNOS(key.getId(), image);
} else if (key.getStorageType() == 2) {
ossImageupload.delOSS(key.getId(), image);
} else if (key.getStorageType() == 3) {
ussImageupload.delUSS(key.getId(), image);
} else if (key.getStorageType() == 4) {
kodoImageupload.delKODO(key.getId(), image);
} else if (key.getStorageType() == 5) {
LocUpdateImg.deleteLOCImg(image);
} else if (key.getStorageType() == 6) {
cosImageupload.delCOS(key.getId(), image);
} else if (key.getStorageType() == 7) {
ftpService.delFTP(key.getId(), image);
} else if (key.getStorageType() == 8) {
s3Imageupload.deleS3(key.getId(), image);
} else {
System.err.println("未获取到对象存储参数,删除失败。");
}
try {
imgAndAlbumService.deleteImgAndAlbum(image.getImgurl());
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
ids.add(image.getId());
} catch (Exception e) {
e.printStackTrace();
System.err.println(image.getImgname() + ":图片数据库记录时发生错误");
}
} catch (Exception e) {
System.err.println("删除的时候发生了一些异常");
// ids.add(Long.valueOf(imgIds[i]));
e.printStackTrace();
}
}
msg.setData(ids);
return msg;
}
}
@@ -1,324 +0,0 @@
package cn.hellohao.utils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* <p>Title: </p>
* <p>Description: </p>
*
* @author Hellohao
* @date 2019年11月10日
*/
public class FTPUtils {
private final Logger LOGGER = LogManager.getLogger(getClass());
private FTPClient ftpClient = null;
private String server;
private int port;
private String userName;
private String userPassword;
public FTPUtils(String server, int port, String userName, String userPassword) {
this.server = server;
this.port = port;
this.userName = userName;
this.userPassword = userPassword;
}
public boolean open() {
// 判断是否已连接
if (ftpClient != null && ftpClient.isConnected()) {
return true;
}
try {
ftpClient = new FTPClient();
// 连接FTP服务器
ftpClient.connect(this.server, this.port);
ftpClient.login(this.userName, this.userPassword);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
Print.warning("FTP服务器拒绝连接.");
this.close();
System.exit(1);
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
return true;
} catch (Exception e) {
this.close();
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 切换到父目录</p>
* <p>Description: </p>
*
* @author Hellohao
* @date 2018年10月11日
*
* @return 切换结果 true:成功, false:失败
*/
private boolean changeToParentDir() {
try {
return ftpClient.changeToParentDirectory();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param dir 目的目录
* @return 切换结果 true:成功,false:失败
*/
private boolean cd(String dir) {
try {
return ftpClient.changeWorkingDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param filePath 指定的目录
* @return 文件列表,或者null
*/
private FTPFile[] getFileList(String filePath) {
try {
return ftpClient.listFiles(filePath);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param ftpPath 目的目录
* @return 切换结果
*/
public boolean changeDir(String ftpPath) {
if (!ftpClient.isConnected()) {
return false;
}
try {
char[] chars = ftpPath.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpPath = sbStr.toString();
if (ftpPath.indexOf('/') == -1) {
// 只有一层目录
ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8"));
} else {
// 多层目录循环创建
String[] paths = ftpPath.split("/");
for (int i = 0; i < paths.length; i++) {
ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8"));
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* @param ftpPath 需要创建的目录
* @return
*/
public boolean mkDir(String ftpPath) {
if (!ftpClient.isConnected()) {
return false;
}
try {
// 将路径中的斜杠统一
char[] chars = ftpPath.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpPath = sbStr.toString();
if (ftpPath.indexOf('/') == -1) {
// 只有一层目录
ftpClient.makeDirectory(new String(ftpPath.getBytes(), "UTF-8"));
ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8"));
} else {
// 多层目录循环创建
String[] paths = ftpPath.split("/");
for (int i = 0; i < paths.length; i++) {
ftpClient.makeDirectory(new String(paths[i].getBytes(), "UTF-8"));
ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8"));
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param //localDirectoryAndFileName 本地文件目录和文件名
* @param ftpFileName 上传到服务器的文件名()
* @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录(目录可以省略)
* @return
*/
public boolean upload(File srcFile, String ftpFileName, String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
boolean flag = false;
if (ftpClient != null) {
FileInputStream fis = null;
try {
fis = new FileInputStream(srcFile);
// 创建目录
this.mkDir(ftpDirectory);
ftpClient.setBufferSize(100000);
ftpClient.setControlEncoding("UTF-8");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
if (ftpFileName == null || ftpFileName == "") {
ftpFileName = srcFile.getName();
}
// 上传
flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "UTF-8"), fis);
} catch (Exception e) {
this.close();
e.printStackTrace();
return false;
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* @param ftpDirectoryAndFileName ftp服务器文件路径,以/dir形式开始
* @param localDirectoryAndFileName 保存到本地的目录
* @return
*/
public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
ftpClient.enterLocalPassiveMode();
try {
// 将路径中的斜杠统一
char[] chars = ftpDirectoryAndFileName.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpDirectoryAndFileName = sbStr.toString();
String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));
String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
this.changeDir(filePath);
ftpClient.retrieveFile(new String(fileName.getBytes(), "UTF-8"), new FileOutputStream(localDirectoryAndFileName)); // download
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param pathName
* @return
*/
public String[] getFileNameList(String pathName) {
try {
return ftpClient.listNames(pathName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* <p>Title: 删除FTP上的文件</p>
* <p>Description: </p>
* @param ftpDirAndFileName 路径开头不能加/,比如应该是test/filename1
* @return
*/
public boolean deleteFile(String ftpDirAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.deleteFile(ftpDirAndFileName);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* @param ftpDirectory
* @return
*/
public boolean deleteDirectory(String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.removeDirectory(ftpDirectory);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 关闭链接</p>
* <p>Description: </p>
*/
public void close() {
try {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
+61 -20
View File
@@ -1,11 +1,15 @@
package cn.hellohao.utils;
import cn.hellohao.config.GlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Properties;
import java.util.UUID;
@@ -16,7 +20,7 @@ import java.util.UUID;
*/
@Configuration
public class FirstRun implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(FirstRun.class);
@Value("${spring.datasource.username}")
private String jdbcusername;
@@ -26,19 +30,33 @@ public class FirstRun implements InitializingBean {
@Value("${spring.datasource.url}")
private String jdbcurl;
@Value("${DockerWebHost}")
private String DockerWebHost;
@Override
public void afterPropertiesSet() {
if(!DockerWebHost.contains("null")){
contentToTxt("/hellohaotbed/webapps/hellohao/config.json", "{\"serverHost\": \""+DockerWebHost+"\"}");
}
isWindows();
RunSqlScript.USERNAME = jdbcusername;
RunSqlScript.PASSWORD = jdbcpass;
RunSqlScript.DBURL = jdbcurl;
Print.Normal("正在校验数据库参数...");
logger.info("正在校验数据库参数...");
RunSqlScript.RunInsert(dynamic);
RunSqlScript.RunInsert(compressed);
String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
RunSqlScript.RunInsert("update user set uid='"+uid+"' where id = 1");
Integer ret0 =
RunSqlScript.RunSelectCount(judgeTable + "'keys' and column_name = 'Region'");
if (ret0 == 0) {
RunSqlScript.RunInsert(sql0);
Print.Normal("Add keys.Region||RootPath");
}
Integer ret1 = RunSqlScript.RunSelectCount(sql1);
if(ret1==0){
Print.Normal("In execution...");
@@ -75,11 +93,7 @@ public class FirstRun implements InitializingBean {
RunSqlScript.RunInsert(sql8);
Print.Normal("Stage 6");
}
Integer ret5 = RunSqlScript.RunSelectCount(judgeTable+"'config' and column_name = 'theme'");
if(ret5==0){
RunSqlScript.RunInsert(sql9);
Print.Normal("Stage 7");
}
Integer ret6 = RunSqlScript.RunSelectCount(judgeTable+" 'user' and column_name = 'token'");
if(ret6==0){
RunSqlScript.RunInsert(sql12);
@@ -91,17 +105,14 @@ public class FirstRun implements InitializingBean {
RunSqlScript.RunInsert(instartAppclient);
Print.Normal("Add table.appclient");
}
// Integer ret6 = RunSqlScript.RunSelectCount(judgeTable+" 'imgdata' and column_name = 'idname'");
// if(ret6==0){
// RunSqlScript.RunInsert(sql11);
// Print.Normal("Add imgdata.idname");
// }
RunSqlScript.RunInsert("alter table `config` modify column `explain` text,modify column `links` text,modify column `notice` text,modify column `baidu` text");
//RunSqlScript.RunInsert("alter table imgdata drop index index_md5key_url");
RunSqlScript.RunInsert(inddx_md5key);
RunSqlScript.RunInsert("UPDATE `keys` SET `Endpoint` = '0' WHERE `id` = 8");
Integer isconfdata = RunSqlScript.RunSelectCount(isTableName+"'confdata'");
if(isconfdata==0){
RunSqlScript.RunInsert(createConfdata);
RunSqlScript.RunInsert(instartConfdata);
Print.Normal("Add table.confdata");
}
// RunSqlScript.RunInsert(inddx_md5key);
RunSqlScript.RunInsert("ALTER TABLE tbed.`user` MODIFY id int auto_increment;");
Print.Normal("Stage success");
clears();
@@ -111,6 +122,8 @@ public class FirstRun implements InitializingBean {
private String isTableName = "SELECT count(table_name) FROM information_schema.TABLES WHERE TABLE_SCHEMA='tbed' and table_name =";
private String judgeTable = "select count(*) from information_schema.columns where TABLE_SCHEMA='tbed' and table_name = ";
//创建blacklist 2019-11-29
private String sql0 =
"alter table `keys` add (Region varchar(255) DEFAULT null,RootPath varchar(255) DEFAULT '/');";
private String sql1 = "select count(*) from information_schema.columns where table_name = 'uploadconfig' and column_name = 'blacklist'";
private String sql2 = "alter table uploadconfig add blacklist varchar(500);";
//创建imgandalbum和album 添加imgdata表字段explain 2019-12-20
@@ -121,7 +134,6 @@ public class FirstRun implements InitializingBean {
private String sql7 = "alter table album add userid int(10)";
//添加imgdata表字段md5key
private String sql8 = "alter table imgdata add md5key varchar(5000)";
private String sql9 = "ALTER TABLE config ADD theme int(4) DEFAULT '1' COMMENT '主题' ";
// 图片标识名字段
private String sql11 = "alter table `imgdata` add idname varchar(255) DEFAULT '未命名' ;";
@@ -129,7 +141,10 @@ public class FirstRun implements InitializingBean {
//创建客户端程序相关表
private String createAppclient = "CREATE TABLE `appclient` (`id` varchar(10) NOT NULL,`isuse` varchar(10) NOT NULL,`winpackurl` varchar(255) NULL DEFAULT NULL,`macpackurl` varchar(255) NULL DEFAULT NULL,`appname` varchar(20) NULL,`applogo` varchar(255) NULL,`appupdate` varchar(10) NOT NULL) ";
private String instartAppclient = "INSERT INTO `appclient` VALUES ('app', 'on', NULL, NULL, 'Hellohao图像托管', 'https://hellohao.nos-eastchina1.126.net/TbedClient/app.png', '1.0.1');";
//创建confdata表
private String createConfdata = "CREATE TABLE tbed.confdata ( `key` varchar(100) NULL, jsondata LONGTEXT NULL )";
private String instartConfdata =
"INSERT INTO `confdata` VALUES ('config', '{\\\"sourcekey\\\":7,\\\"emails\\\":1,\\\"webname\\\":\\\"Hellohao图床\\\",\\\"explain\\\":\\\"Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。\\\",\\\"links\\\":\\\"<p style=\\\\\\\"color:#7c7c88;\\\\\\\">© 2019 <a href=\\\\\\\"http://www.Hellohao.cn/\\\\\\\" target=\\\\\\\"_blank\\\\\\\" title=\\\\\\\"Hellohao\\\\\\\">Hellohao</a><span> - All Rights Reserved</span> </p>\\\",\\\"notice\\\":\\\"也许...|这将是最好用的图床|为了更好的用户体验,建议您注册本站继续免费使用Hellohao图床。本站不得上传任何形式的非法图片,一旦发现,永久删除并禁封账户。情节严重者将相关资料交于相关部门处理。\\\",\\\"domain\\\":\\\"http://127.0.0.1:10088\\\",\\\"background1\\\":\\\"\\\",\\\"sett\\\":\\\"1\\\",\\\"webms\\\":\\\"Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。\\\",\\\"webkeywords\\\":\\\"hellohao图床,图床,图片上传,开源图床,hellohao,图像托管,图片分享\\\",\\\"theme\\\":2,\\\"websubtitle\\\":\\\"这将是你用过最优秀的图像托管程序\\\",\\\"logo\\\":null,\\\"aboutinfo\\\":\\\"<img width=\\\\\\\"300px\\\\\\\" src=\\\\\\\"http://img.wwery.com/hellohao/rPscRYwz.png\\\\\\\"> <br /> <br /> <p>也许,这将是你用到最优秀的图像托管程序</p> <p>本程序为Hellohao图象托管程序</p> <br/> <p style=\\\\\\\"color: #656565;\\\\\\\">作者:hellohao独立开发</p> <p style=\\\\\\\"color: #656565;\\\\\\\">www.hellohao.cn</p>\\\"}');";
private String inddx_md5key = "ALTER TABLE imgdata ADD INDEX index_md5key_url ( md5key,imgurl)";
// create index yarn_app_result_i4 on yarn_app_result (flow_exec_id(100), another_column(50));
@@ -167,4 +182,30 @@ public class FirstRun implements InitializingBean {
return System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
}
public static void contentToTxt(String filePath, String content) {
// String str = new String(); //原有txt内容
String s1 = new String();//内容更新
try {
File f = new File(filePath);
if (f.exists()) {
System.out.print("文件存在");
} else {
System.out.print("文件不存在");
f.createNewFile();// 不存在则创建
}
// BufferedReader input = new BufferedReader(new FileReader(f));
// while ((str = input.readLine()) != null) {
// s1 += str + "\n";
// }
// input.close();
s1 += content + "\n";
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+22 -11
View File
@@ -3,7 +3,8 @@ package cn.hellohao.utils;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.service.impl.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.Map;
@@ -13,15 +14,25 @@ import java.util.Map;
* @version 1.0
* @date 2019/11/7 17:12
*/
@Service
public class GetSource {
public static ReturnImage storageSource(Integer type, Map<Map<String, String>, File> fileMap, String userpath,Integer keyID){
NOSImageupload nosImageupload = SpringContextHolder.getBean(NOSImageupload.class);
OSSImageupload ossImageupload = SpringContextHolder.getBean(OSSImageupload.class);
USSImageupload ussImageupload = SpringContextHolder.getBean(USSImageupload.class);
KODOImageupload kodoImageupload = SpringContextHolder.getBean(KODOImageupload.class);
COSImageupload cosImageupload = SpringContextHolder.getBean(COSImageupload.class);
FTPImageupload ftpImageupload = SpringContextHolder.getBean(FTPImageupload.class);
UFileImageupload uFileImageupload = SpringContextHolder.getBean(UFileImageupload.class);
@Autowired
NOSImageupload nosImageupload;
@Autowired
OSSImageupload ossImageupload;
@Autowired
USSImageupload ussImageupload;
@Autowired
KODOImageupload kodoImageupload;
@Autowired
COSImageupload cosImageupload;
@Autowired
FtpServiceImpl ftpService;
@Autowired
S3Imageupload s3Imageupload;
public ReturnImage storageSource(Integer type, Map<Map<String, String>, File> fileMap, String userpath,Integer keyID){
ReturnImage returnImage = null;
try {
if(type==1){
@@ -37,9 +48,9 @@ public class GetSource {
}else if(type==6){
returnImage = cosImageupload.ImageuploadCOS(fileMap, userpath,keyID);;
}else if(type==7){
returnImage = ftpImageupload.ImageuploadFTP(fileMap, userpath,keyID);
returnImage = ftpService.FtpUploadFile(fileMap, userpath,keyID);
}else if(type==8){
returnImage = uFileImageupload.ImageuploadUFile(fileMap, userpath,keyID);
returnImage = s3Imageupload.ImageuploadS3(fileMap, userpath,keyID);
}
else{
new StorageSourceInitException("GetSource类捕捉异常:未找到存储源");
@@ -1,14 +1,15 @@
package cn.hellohao.utils;
import cn.hellohao.pojo.Config;
import cn.hellohao.pojo.EmailConfig;
import cn.hellohao.pojo.Msg;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import io.github.biezhi.ome.OhMyEmail;
import org.springframework.core.io.ClassPathResource;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
@@ -18,7 +19,7 @@ import java.util.UUID;
public class NewSendEmail {
public static Integer sendEmail(EmailConfig emailConfig, String username, String uid, String toEmail, Config config) {
public static Integer sendEmail(EmailConfig emailConfig, String username, String uid, String toEmail, JSONObject jsonObject) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
@@ -33,8 +34,8 @@ public class NewSendEmail {
// OhMyEmail.config(OhMyEmail.SMTP_QQ(false), "xxxx@qq.com", "your@password");
OhMyEmail.config(props, emailConfig.getEmails(), emailConfig.getEmailkey());
String webname=config.getWebname();
String domain = config.getDomain();
String webname=jsonObject.getString("webname");
String domain = jsonObject.getString("domain");
try {
//生成模板
PebbleEngine engine = new PebbleEngine.Builder().build();
@@ -90,7 +91,7 @@ public class NewSendEmail {
}
public static Integer sendEmailFindPass(EmailConfig emailConfig,String username, String uid, String toEmail, Config config) {
public static Integer sendEmailFindPass(EmailConfig emailConfig,String username, String uid, String toEmail, JSONObject jsonObject) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
@@ -103,8 +104,8 @@ public class NewSendEmail {
// 配置一次即可,可以配置为静态方法
// OhMyEmail.config(OhMyEmail.SMTP_QQ(false), "xxxx@qq.com", "your@password");
OhMyEmail.config(props, emailConfig.getEmails(), emailConfig.getEmailkey());
String webname=config.getWebname();
String domain = config.getDomain();
String webname=jsonObject.getString("webname");
String domain = jsonObject.getString("domain");
String new_pass = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,10);
try {
//生成模板
@@ -1,11 +1,6 @@
package cn.hellohao.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
final class RunSqlScript {
@@ -1,64 +1,6 @@
package cn.hellohao.utils;
import cn.hellohao.pojo.Keys;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
public class StringUtils {
//此方法目前未使用2020-04-06
public static Boolean doNull(Integer sourcekey,Keys k) {
if(sourcekey==1){
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ){
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ){
return true;
}
}
}else if(sourcekey==2){
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
return true;
}
}
}else if(sourcekey==3){
if(k.getEndpoint()!=null && k.getAccessSecret()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
return true;
}
}
}else if(sourcekey==4){
if (k.getEndpoint() != null && k.getAccessSecret() != null && k.getEndpoint() != null
&& k.getBucketname() != null && k.getRequestAddress() != null) {
if (!k.getEndpoint().equals("") && !k.getAccessSecret() .equals("") && !k.getEndpoint() .equals("")
&& !k.getBucketname() .equals("") && !k.getRequestAddress().equals("")) {
return true;
}
}
}else if(sourcekey==6){
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
return true;
}
}
}else if(sourcekey==7){
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") && !k.getRequestAddress().equals("") ) {
return true;
}
}
}
return false;
}
/**
* 移除 URL 中的第一个 '/'
* @return 如 path = '/folder1/file1', 返回 'folder1/file1'
@@ -7,7 +7,7 @@ public class MyProgress {
private int delSuccessCount=0;//已经成功的个数
private List<String> delErrorImgListt = new ArrayList<>();//已经失败的图片
private int delOCT=0; //控制开关
private List<Integer> delSuccessImgList = new ArrayList<>(); //删除成功的图片
private List<Long> delSuccessImgList = new ArrayList<>(); //删除成功的图片
public void InitializeDelImg(){
this.delSuccessCount=0;//已经成功的个数
@@ -19,7 +19,7 @@ public class MyProgress {
public MyProgress() {
}
public MyProgress(int delSuccessCount, List<String> delErrorImgListt, int delOCT, List<Integer> delSuccessImgList) {
public MyProgress(int delSuccessCount, List<String> delErrorImgListt, int delOCT, List<Long> delSuccessImgList) {
this.delSuccessCount = delSuccessCount;
this.delErrorImgListt = delErrorImgListt;
this.delOCT = delOCT;
@@ -50,11 +50,11 @@ public class MyProgress {
this.delOCT = delOCT;
}
public List<Integer> getDelSuccessImgList() {
public List<Long> getDelSuccessImgList() {
return delSuccessImgList;
}
public void setDelSuccessImgList(List<Integer> delSuccessImgList) {
public void setDelSuccessImgList(List<Long> delSuccessImgList) {
this.delSuccessImgList = delSuccessImgList;
}
+17 -11
View File
@@ -1,31 +1,36 @@
DockerWebHost=${HELLOHAO_SERVER_HOST:null}
#端口
server.port=10088
#前端域名需要带协议头http(s)://
CROS_ALLOWED_ORIGINS=${HELLOHAO_WEB_HOST:http://127.0.0.1:8080}
#数据库账号
spring.datasource.username=root
#数据库密码test
spring.datasource.password=root
spring.datasource.password=${MYSQL_PASS:root}
#数据库链接地址
spring.datasource.url=jdbc:mysql://localhost:3306/tbed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
#端口
server.port=8089
#前端域名需要带协议头http(s)://
CROS_ALLOWED_ORIGINS=http://127.0.0.1:8080
spring.datasource.url=${MYSQL_URL:jdbc:mysql://127.0.0.1:3306/tbed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8}
#MySQL Driver 无需修改
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.redis.host= 127.0.0.1
spring.redis.port=6379
## 设置最大连接数,0为无限
spring.redis.pool.max-active=8
# 连接超时时间(毫秒)
spring.redis.timeout=5000
spring.redis.password=
#下边的配置项不需要修改。
#logging.config=classpath:logback-spring.xml
#logging.file.path=/HellohaoData/tbedlog
spring.thymeleaf.suffix=.html
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.cn.hellohao.dao=debug
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.thymeleaf.cache=false
multipart.maxFileSize=10240KB
multipart.maxRequestSize=10240KB
spring.thymeleaf.mode = LEGACYHTML5
spring.http.multipart.location=/data/upload_tmp
systemupdate=2020-05-26
spring.datasource.druid.filter.config.enabled=false
@@ -43,4 +48,5 @@ spring.datasource.druid.stat-view-servlet.login-username=hellohao@dealer
spring.datasource.druid.stat-view-servlet.login-password=52BNmXPJL0rQQ3CU
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
spring.datasource.druid.web-stat-filter.exclusions=false
#log4j.logger.cn.hellohao.dao=DEBUG
log4j2.formatMsgNoLookups=True
+1 -1
View File
@@ -5,7 +5,7 @@
\/ /_/ \___|_|_|\___/|_| |_|\__,_|\___/
__________________________________________
HellohaoBloghttp://www.hellohao.cn
Hellohao图像托管https://www.hellohao.cn
__________________________________________
//
+121 -174
View File
@@ -1,197 +1,144 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!-- 级别从高到低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->
<!-- 日志输出规则 根据当前ROOT 级别,日志输出时,级别高于root默认的级别时 会输出 -->
<!-- 以下 每个配置的 filter 是过滤掉输出文件里面,会出现高级别文件,依然出现低级别的日志信息,通过filter 过滤只记录本级别的日志 -->
<!-- scan 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 -->
<!-- scanPeriod 设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug 当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<!-- 动态日志级别 -->
<jmxConfigurator/>
<property name="log.path" value="/HellohaoData/tbedlog" />
<!-- 定义日志文件 输出位置 -->
<property name="log.log_dir" value="logs"/>
<property name="log.log_name" value="log"/>
<!-- 日志最大的历史 30天 -->
<property name="log.maxHistory" value="30"/>
<property name="log.level" value="debug"/>
<property name="log.maxSize" value="5MB" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<!-- ConsoleAppender 控制台输出日志 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<!-- <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
<!-- &lt;!&ndash; 设置过滤级别 &ndash;&gt;-->
<!-- <level>INFO</level>-->
<!-- &lt;!&ndash; 用于配置符合过滤条件的操作 &ndash;&gt;-->
<!-- <onMatch>ACCEPT</onMatch>-->
<!-- &lt;!&ndash; 用于配置不符合过滤条件的操作 &ndash;&gt;-->
<!-- <onMismatch>DENY</onMismatch>-->
<!-- </filter>-->
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
<pattern>
<!-- 设置日志输出格式 -->
<!-- 日期 [线程] [class类]-[日志级别] log内容 -->
%blue(%d{yyyy-MM-dd HH:mm:ss,SSS}) [%cyan(%t)] [%yellow(%c)]-[%highlight(%p)] %m%n
</pattern>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<!-- ERROR级别日志 -->
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 RollingFileAppender -->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<!-- 过滤器,只记录WARN级别的日志 -->
<!-- 果日志级别等于配置级别,过滤器会根据onMath 和 onMismatch接收或拒绝日志。 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 设置过滤级别 -->
<level>ERROR</level>
<!-- 用于配置符合过滤条件的操作 -->
<onMatch>ACCEPT</onMatch>
<!-- 用于配置不符合过滤条件的操作 -->
<onMismatch>DENY</onMismatch>
</filter>
<!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责触发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志输出位置 可相对、和绝对路径 -->
<fileNamePattern>
${log.log_dir}/error/%d{yyyy-MM-dd}/error_${log.log_name}-%i.log
</fileNamePattern>
<!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件,假设设置每个月滚动,且<maxHistory>是6
则只保存最近6个月的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除 -->
<maxHistory>${log.maxHistory}</maxHistory>
<!--日志文件最大的大小-->
<MaxFileSize>${log.maxSize}</MaxFileSize>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<pattern>
<!-- 设置日志输出格式 -->
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</encoder>
</appender>
<!-- INFO级别日志 appender -->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/log_info.log</file>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.log_dir}/info/%d{yyyy-MM-dd}/info_${log.log_name}-%i.log</fileNamePattern>
<maxHistory>${log.maxHistory}</maxHistory>
<MaxFileSize>${log.maxSize}</MaxFileSize>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %logger - %msg%n</pattern>
</encoder>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!-- DEBUG级别日志 appender -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/log_debug.log</file>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.log_dir}/debug/%d{yyyy-MM-dd}/debug_${log.log_name}-%i.log</fileNamePattern>
<maxHistory>${log.maxHistory}</maxHistory>
<MaxFileSize>${log.maxSize}</MaxFileSize>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %logger - %msg%n</pattern>
</encoder>
</appender>
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--设置一个向上传递的appender,所有级别的日志都会输出-->
<!-- <appender name="app" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${log.log_dir}/app/%d{yyyy-MM-dd}/app_${log.log_name}-%i.log</fileNamePattern>-->
<!-- <maxHistory>${log.maxHistory}</maxHistory>-->
<!-- <MaxFileSize>${log.maxSize}</MaxFileSize>-->
<!-- <cleanHistoryOnStart>true</cleanHistoryOnStart>-->
<!-- </rollingPolicy>-->
<!-- <encoder>-->
<!-- <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %logger - %msg%n</pattern>-->
<!-- </encoder>-->
<!-- </appender>-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="cn.hellohao.dao" level="debug"/>
</springProfile>
<root level="info">
<!--name包下的类的日志输出-->
<logger name="cn.hellohao" additivity="false" level="DEBUG" >
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
<appender-ref ref="INFO" />
<appender-ref ref="DEBUG" />
<appender-ref ref="ERROR" />
</logger>
<logger name="proxy.system.log" additivity="false">
<appender-ref ref="INFO" />
<appender-ref ref="DEBUG" />
<appender-ref ref="ERROR" />
</logger>
<!--生产环境:输出到文件-->
<!--<springProfile name="pro">-->
<!--<root level="info">-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="DEBUG_FILE" />-->
<!--<appender-ref ref="INFO_FILE" />-->
<!--<appender-ref ref="ERROR_FILE" />-->
<!--<appender-ref ref="WARN_FILE" />-->
<!--</root>-->
<!--</springProfile>-->
</configuration>
<!-- root级别 DEBUG -->
<!-- <root level="DEBUG">-->
<!-- </root>-->
</configuration>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hellohao.dao.ConfdataMapper">
<select id="selectConfdata" resultType="cn.hellohao.pojo.Confdata">
select * from confdata where `key`=#{key}
</select>
<update id="updateConfdata" parameterType="cn.hellohao.pojo.Confdata">
UPDATE confdata
<set>
<if test="jsondata != null">
jsondata = #{jsondata},
</if>
</set>
where `key`=#{key}
</update>
</mapper>
@@ -1,79 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hellohao.dao.ConfigMapper">
<select id="getSourceype" resultType="cn.hellohao.pojo.Config">
select * from config where id = 1
</select>
<update id="setSourceype" parameterType="cn.hellohao.pojo.Config">
UPDATE config
<set>
<if test="sourcekey != null">
sourcekey = #{sourcekey},
</if>
<if test="emails != null">
emails = #{emails},
</if>
<if test="webname != null">
webname = #{webname},
</if>
<if test="explain != null">
`explain` = #{explain},
</if>
<if test="video != null">
`video` = #{video},
</if>
<if test="backtype != null">
`backtype` = #{backtype},
</if>
<if test="links != null">
`links` = #{links},
</if>
<if test="notice != null">
`notice` = #{notice},
</if>
<if test="baidu != null">
`baidu` = #{baidu},
</if>
<if test="domain != null">
`domain` = #{domain},
</if>
<if test="background1 != null">
`background1` = #{background1},
</if>
<if test="background2 != null">
`background2` = #{background2},
</if>
<if test="sett != null">
`sett` = #{sett},
</if>
<if test="webms != null">
`webms` = #{webms},
</if>
<if test="webkeywords != null">
`webkeywords` = #{webkeywords},
</if>
<if test="webfavicons != null">
`webfavicons` = #{webfavicons},
</if>
<if test="theme != null">
`theme` = #{theme},
</if>
<if test="websubtitle != null">
websubtitle = #{websubtitle},
</if>
<if test="logo != null">
logo = #{logo},
</if>
<if test="aboutinfo != null">
aboutinfo = #{aboutinfo},
</if>
</set>
where id=1
</update>
</mapper>
+7 -3
View File
@@ -121,7 +121,7 @@
select count(*) from imgdata where userid = #{userid}
</select>
<delete id="deleimg" parameterType="integer">
<delete id="deleimg" parameterType="Long">
DELETE FROM imgdata WHERE id=#{id}
</delete>
@@ -129,7 +129,7 @@
DELETE FROM imgdata WHERE imguid = #{imguid}
</delete>
<select id="selectByPrimaryKey" parameterType="integer" resultType="cn.hellohao.pojo.Images">
<select id="selectByPrimaryKey" parameterType="Long" resultType="cn.hellohao.pojo.Images">
select * from imgdata where id = #{id}
</select>
@@ -154,6 +154,10 @@
<if test="idname!=null and idname!=''">
idname=#{idname}
</if>
<if test="violation!=null and violation!=''">
violation=#{violation}
</if>
</set>
where imgname=#{imgname}
</update>
@@ -163,7 +167,7 @@
</delete>
<!-- 批量删除-->
<delete id="deleall" parameterType="integer">
<delete id="deleall" parameterType="Long">
DELETE FROM imgdata WHERE id = #{id}
</delete>
+4 -2
View File
@@ -27,7 +27,7 @@
WHEN storageType=5 THEN '本地'
WHEN storageType=6 THEN '腾讯云'
WHEN storageType=7 THEN 'FTP'
WHEN storageType=8 THEN 'UFile'
WHEN storageType=8 THEN 'S3协议'
ELSE '未知' END AS storageName,
keyname
FROM `keys` GROUP BY storageType,id,storageName,keyname
@@ -49,7 +49,9 @@
Endpoint = #{Endpoint},
Bucketname = #{Bucketname},
RequestAddress = #{RequestAddress},
keyname = #{keyname}
keyname = #{keyname},
Region = #{Region},
RootPath = #{RootPath}
WHERE
storageType = #{storageType}
</update>