40 Commits
Author SHA1 Message Date
tiansh 75d753c53c :fire:修复部分情况不能部署成功问题 2024-03-20 15:10:00 +08:00
tiansh 677c53104a :fire:修复部分情况不能部署成功问题 2024-03-19 17:28:40 +08:00
tiansh 113e69fff2 :fire:优化代码 2024-03-19 11:17:05 +08:00
tiansh 0ede684acb :fire:优化代码 2024-03-11 09:27:07 +08:00
tiansh f0dd1d0db8 📝 2024-01-30 18:47:18 +08:00
tiansh 59aaaa1c82 update:优化上传逻辑,减少性能占用 2024-01-30 18:45:01 +08:00
tiansh f990c4cd80 update:优化上传逻辑,减少性能占用 2024-01-29 17:37:46 +08:00
tiansh 369b88ffb3 update:优化线程池 2024-01-26 09:13:42 +08:00
tiansh bfa41ac049 add:新增webdav相关功能,修复安全隐患 2024-01-24 17:23:37 +08:00
tiansh ca0da1dd06 add:新增webdav相关功能,修复安全隐患 2024-01-23 17:44:21 +08:00
tiansh 44814e79b0 add:新增webdav相关功能,修复安全隐患 2024-01-23 17:41:51 +08:00
hellohao f02d865389 适配WebDAV ing 2024-01-22 22:19:07 +08:00
tiansh 48b0e1c5ca add:新增webdav相关功能 2024-01-22 17:34:47 +08:00
tiansh a04bbc1ea6 📝 2024-01-22 11:26:06 +08:00
tiansh 31b4426c10 📝 2024-01-22 11:13:26 +08:00
tiansh 766c125673 📝 2024-01-22 11:12:27 +08:00
tiansh 0de7e0e0fc 📝 2024-01-22 11:10:06 +08:00
tiansh f24a2d5557 📝 2024-01-22 11:09:21 +08:00
tiansh 87394258ad 📝 2024-01-22 11:08:40 +08:00
hello-hao 89a66a17b3 📝 2024-01-11 17:42:23 +08:00
hello-hao 3e4c90c8d9 :bug:修复上传失败问题 2024-01-11 17:03:48 +08:00
hello-hao fb9f2a896e 📝 2024-01-03 14:00:17 +08:00
hello-hao 9ca8695cfd 📝 2024-01-03 13:59:15 +08:00
hellohao 33d4990ded 更新文档 2024-01-02 23:39:13 +08:00
hello-hao 679ada60bc feat:添加强制删除,优化七牛云对接 2024-01-02 17:33:01 +08:00
hello-hao e2e723eb52 feat:添加强制删除,优化七牛云对接 2023-12-29 17:28:08 +08:00
hello-hao 60db6036a5 📝 2023-10-13 10:02:55 +08:00
hello-hao 790fded8ca :bug:修复了一些功能 2023-09-25 14:03:53 +08:00
hello-hao fc53e4c8ac :snail:优化了一些功能 2023-09-18 17:17:21 +08:00
hello-hao 86ae47e632 📝 2023-08-01 14:33:16 +08:00
hello-hao 241ab625c0 📝 2023-08-01 14:22:05 +08:00
hello-hao 19c2b3ce9f 📝 2023-08-01 14:19:43 +08:00
hellohao c5b800ad56 更新文档 2023-06-22 19:15:06 +08:00
hellohao c960d2a812 update:优化url上传,修复多个问题 2023-06-22 19:12:53 +08:00
hello-hao 7906948ab7 update:优化调整了多个问题 2023-06-21 19:04:59 +08:00
hello-hao 3fce125334 📝 2023-05-23 10:04:38 +08:00
hello-hao 062823ae53 feat:支持查询图像,自动检测新版本 2023-05-19 18:58:57 +08:00
hello-hao 349845e6f1 📝 2023-05-19 18:50:25 +08:00
hello-hao f40f4177f7 📝 2023-05-19 18:41:58 +08:00
hello-hao 17c49157c2 📝 2023-05-19 18:39:22 +08:00
54 changed files with 1304 additions and 940 deletions
-6
View File
@@ -1,6 +0,0 @@
*.js linguist-language=java
*.css linguist-language=java
*.html linguist-language=java
+44 -38
View File
@@ -1,18 +1,29 @@
# Hellohao图像托管程序 - 也许这会是最优秀的图程序
![宣传图Banner](https://upload.cc/i1/2022/02/11/HSg5tX.png)
# Hellohao图像托管 - 也许这会是最优秀的图像托管程序
<p align="center">
<a href="https://www.hellohao.cn/" target="_blank">
<img width="1920px" src="https://upload.cc/i1/2022/02/11/HSg5tX.png">
</a>
</p>
![Visual Studio Marketplace Rating (Stars)](https://img.shields.io/visual-studio-marketplace/stars/ritwickdey.LiveServer?style=flat-square)
![https://img.shields.io/badge/license-AGPL-blue.svg?style=flat-square](https://img.shields.io/badge/license-AGPL-blue.svg?longCache=true&style=flat-square)
![https://img.shields.io/badge/language-java-orange.svg?style=flat-square](https://img.shields.io/badge/language-java-yellow.svg?longCache=true&style=popout-square)
<h3 align="center">赞助商</h3>
<p align="center">
<a href="https://www.eltyun.com/" target="_blank">
<img width="350px" src="https://t.tdo.ink/hellohao/s9ugmihq.png">
</a>
</p>
>:exclamation: 托管的所有开源代码可能存在作者修改/测试/调整等行为,均为实验性代码,故并不保证程序或功能的可用性,如果你想要部署程序,请下载我们提供的编译整合包进行安装部署。
### 引导
[官网](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)
[官网](https://tbed.hellohao.cn) | [文档](https://doc.hellohao.cn) | [演示站](https://pic.hellohao.cn) | [桌面客户端](https://tbed.hellohao.cn/app) | [微信小程序](https://tbed.hellohao.cn/wechat) | [前端源码](https://github.com/Hello-hao/tbed-web)
### 前言
@@ -23,22 +34,16 @@
**存储源支持:**
开源版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,~~`U-File`~~,`FTP`,`AWS S3协议`(`百度云BOS`,`青云Qingstor`,`Ucloud US3`,`Minio`等兼容S3协议)
开源版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,`FTP`,`AWS S3协议`(`百度云BOS`,`青云Qingstor`,`Ucloud US3`,`Minio`等兼容S3协议)
[Core版](https://hellohao.cn):开源版的基础上增加`Backblaze(B2)` 并且可同个对象存储商家可开多个存储源(可添加至90+存储源)
### 更新日志 `20230320`
- 修复了修改/保存存储源时,状态不能及时更新
- 优化移动端后台状态栏遮罩关闭异常的情况
- 修复百度图像鉴别不能使用的情况,鉴别违规图像不自动删除的情况
- 优化图像鉴别线程池配置
- 适配移动端页面首页状态栏
- 新增支持Docker-compose方式部署程序
[Core版](https://hellohao.cn):开源版的基础上增加`Backblaze(B2)` 并且可`同个对象存储商家`可开多个存储源(可添加至90+存储源)
[^_^]: 程序宣传视频:[自制宣传视频](https://www.bilibili.com/video/BV11r4y1y7mH/)
### 更新日志 `20240319`
- 修复部分部署场景部署不成功的问题
- 提高系统稳定性
### 主要功能
@@ -97,7 +102,8 @@
version: "3"
services:
tbed-free:
image: hellohao/tbed-free:20230320
# 具体版本号需要填写目前发行的最新版本
image: hellohao/tbed-free:2023xxxx
networks:
hellohao_network:
ports:
@@ -107,6 +113,8 @@
- /HellohaoData/:/HellohaoData/
environment:
MYSQL_URL: jdbc:mysql://hellohaodb/tbed?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
# 数据库用户名(一般使用本镜像数据库无需修改,如果使用外部三方数据库自行修改自己的用户名)
MYSQL_USERNAME: root
# 自定设置一个MySQL的密码,请保证与下方 POSTGRES_PASSWORD 的变量值一致
MYSQL_PASS: tIaNGg@SHa&hIo56
# 前端域名(反代10089端口的域名)
@@ -143,6 +151,8 @@
更多部署教程参考程序[相关文档](http://doc.hellohao.cn)
更强大的功能可[购买Core版](http://tbed.hellohao.cn/pay)程序
### 启动项目
> 访问你的前端域名即可
@@ -154,7 +164,7 @@
### 系统预览
![首页](https://upload.cc/i1/2022/02/11/t2wCEF.png)
![首页](https://upload.cc/i1/2023/05/23/Lsdivj.png)
![控制台详情](https://upload.cc/i1/2022/02/11/Al8UrH.png)
@@ -164,17 +174,22 @@
![站点设置](https://upload.cc/i1/2022/02/11/Hj7pWM.png)
[^_^]: ![首页](http://img.wwery.com/Hellohao/xI9TSKcI.png)
[^_^]: ![控制台详情](http://img.wwery.com/Hellohao/klytOMWr.png)
[^_^]: ![相册](http://img.wwery.com/Hellohao/2UQkXTHw.png)
[^_^]: ![多存储源](http://img.wwery.com/Hellohao/xXSMlsTg.png)
[^_^]: ![站点设置](http://img.wwery.com/Hellohao/n5zXistG.png)
### 桌面客户端(win/mac)
> 获取地址:[官网获取](https://www.hellohao.cn/app)
### 客户端(win64/mac)
> 目前已经正式上线
> `开源版`/`Core版` 都可以使用
> ![桌面客户端软件](https://upload.cc/i1/2022/07/13/5W8Pxh.png)
### 微信小程序
> 仅适用于对接`Core付费版`,开源版暂不可对接使用。
> 获取地址:[官网获取](https://www.hellohao.cn/pay)
![Hellohao图像托管](https://hellohao.cn/newassets/img/twechat.png)
[//]: # "![Hellohao图像托管]&#40;https://upload.cc/i1/2022/03/28/Vnp0bT.png&#41;"
### 运行环境
@@ -200,17 +215,9 @@
- JWT认证
- Shiro
### 微信小程序
> 目前已有测试版,更多功能开发中,开发进度的快慢要根据作者的工作压力、心情状况等自身情况进行评估。
> 暂时无法给出具体发布小程序的时间。大家期待吧。
![Hellohao图像托管](https://upload.cc/i1/2022/03/28/Vnp0bT.png)
[^_^]: ![小程序UI](https://upload.cc/i1/2022/02/11/6kPmr8.png)
### 声明
Hellohao图像托管已申请[**中国国家版权局计算机软件著作权**](https://register.ccopyright.com.cn/query.html)登记,受法律法规保护。
> 登记号:2023SR1210640
本项目遵循[GNU Affero General Public License v3.0](https://choosealicense.com/licenses/agpl-3.0/#)开源协议,使用前请悉知。
如果你想商用或程序定制,请先与我们联系,分享你的利益。
@@ -228,4 +235,3 @@
**如需程序定制或其他业务,请与我们取得联系**
[Hellohao图像托管官网](http://hellohao.cn)
+13 -3
View File
@@ -130,7 +130,17 @@
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.5.1</version>
</dependency>
<!-- webdav-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>com.github.lookfirst</groupId>
<artifactId>sardine</artifactId>
<version>5.10</version>
</dependency>
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
@@ -196,7 +206,7 @@
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.22</version>
<version>7.14.0</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
@@ -238,7 +248,7 @@
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>8</source><target>8</target></configuration></plugin>
</plugins>
</build>
@@ -17,6 +17,8 @@ import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
import javax.sql.DataSource;
import java.net.InetAddress;
import java.net.Socket;
import java.util.stream.Stream;
@SpringBootApplication
@@ -10,10 +10,12 @@ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* @author Hellohao
@@ -33,7 +35,6 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
String serviceName = httpServletRequest.getServletPath();//获取接口
String Users_Origin = httpServletRequest.getHeader("usersOrigin");
String token = httpServletRequest.getHeader("Authorization");
//验证前端域名
if(httpServletRequest.getMethod().equals("POST") && !serviceName.contains("/api") && !serviceName.contains("/verifyCode")
&& !serviceName.contains("/getClientVersion") && !serviceName.contains("/client")){
try{
@@ -73,7 +74,6 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(userData.getEmail(),userData.getPassword());
tokenOBJ.setRememberMe(true);
//执行登录方法,如果没有异常,说明登录成功
subject.login(tokenOBJ);
SecurityUtils.getSubject().getSession().setTimeout(3600000);
User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
@@ -100,7 +100,6 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
subject.login(tokenOBJ);
SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时
} catch (Exception e) {
// System.err.println("拦截器,登录失败,false");
this.CODE = "403";
return false;
}
@@ -139,11 +138,16 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
info = "用户未找到";
}
System.err.println("拦截器False-"+info);
response.setContentType("application/json;charset=UTF-8");
final JSONObject jsonObject = new JSONObject();
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
PrintWriter writer = httpServletResponse.getWriter();
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",this.CODE);
jsonObject.put("info",info);
response.getWriter().write(jsonObject.toJSONString());
writer.write(jsonObject.toJSONString());
writer.flush();
} catch (Exception e) {
System.out.println("返回token验证失败403请求,报异常了");
}
@@ -31,7 +31,9 @@ public class ShiroConfig {
filterMap.put("/verifyCode","anon");
filterMap.put("/verifyCodeForRegister","anon");
filterMap.put("/verifyCodeForRetrieve","anon");
filterMap.put("/verifyCodeFortowSendEmail","anon");
filterMap.put("/api/**","anon");
filterMap.put("/w/**","anon");
filterMap.put("/user/**","anon");
filterMap.put("/ota/**","anon");
filterMap.put("/admin/root/**","roles[admin]");
@@ -2,6 +2,7 @@ package cn.hellohao.auth.shiro;
import cn.hellohao.pojo.User;
import cn.hellohao.service.UserService;
import cn.hellohao.utils.SetText;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
@@ -46,7 +47,11 @@ public class UserRealm extends AuthorizingRealm {
UsernamePasswordToken userToken = null;
userToken = (UsernamePasswordToken)tokenOBJ;
User user = new User();
user.setEmail(userToken.getUsername());
if(SetText.checkEmail(userToken.getUsername())){
user.setEmail(userToken.getUsername());
}else{
user.setUsername(userToken.getUsername());
}
User u = userService.getUsers(user);
if(u==null){
return null;
@@ -8,7 +8,6 @@ import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@@ -24,7 +23,7 @@ public class JWTUtil {
public static String createToken(User user){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,604800 );//单位秒604800 为7天
calendar.add(Calendar.SECOND,2592000 );//单位秒
Algorithm algorithm = Algorithm.HMAC256(SECRET);
String token = JWT.create()
.withClaim("email", user.getEmail())
@@ -16,9 +16,9 @@ public class PoolConfig {
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getCorePoolSize());
executor.setMaxPoolSize(properties.getMaxPoolSize());
executor.setQueueCapacity(properties.getQueueCapacity());
executor.setCorePoolSize(properties.getCorePoolSize()); //设置核心线程数
executor.setMaxPoolSize(properties.getMaxPoolSize()); //设置最大线程数
executor.setQueueCapacity(properties.getQueueCapacity()); //设置队列容量
executor.setThreadNamePrefix(properties.getThreadNamePrefix());
executor.setKeepAliveSeconds(properties.getKeepAliveTime());
executor.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown());
@@ -42,7 +42,7 @@ public class PoolConfig {
private int corePoolSize = 5;
private int maxPoolSize = 50;
private int keepAliveTime = 15;
private int queueCapacity = 6;
private int queueCapacity = 10;
private String threadNamePrefix = "Tbed-Thread";
private boolean allowCoreThreadTimeout = false;
private boolean waitForTasksToCompleteOnShutdown = false;
@@ -7,7 +7,6 @@ import cn.hellohao.service.*;
import cn.hellohao.service.impl.AlbumServiceImpl;
import cn.hellohao.service.impl.UserServiceImpl;
import cn.hellohao.service.impl.deleImages;
import cn.hellohao.utils.Base64Encryption;
import cn.hellohao.utils.SetFiles;
import cn.hellohao.utils.SetText;
import cn.hellohao.utils.progress.MyProgress;
@@ -28,10 +27,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.*;
/**
* @author Hellohao
@@ -313,6 +309,7 @@ public class AdminController {
String starttime = jsonObj.getString("starttime");
String stoptime = jsonObj.getString("stoptime");
String selectUserType = jsonObj.getString("selectUserType"); // me/all
String order = jsonObj.getString("order");
String username = jsonObj.getString("username");
String searchname = jsonObj.getString("searchname");
Integer selecttype = jsonObj.getInteger("selecttype");
@@ -359,6 +356,7 @@ public class AdminController {
if(!StringUtils.isBlank(searchname)){
img.setSearchname(searchname);
}
img.setOrder(StringUtils.isBlank(order)?"desc":order);
List<Images> images = imgService.selectimg(img);
PageInfo<Images> rolePageInfo = new PageInfo<>(images);
PageResultBean<Images> pageResultBean =
@@ -407,9 +405,15 @@ public class AdminController {
return msg;
}
String regex = "^\\w+$";
if (username.length() > 20 || !username.matches(regex)) {
if (username.length() > 30) {
msg.setCode("110403");
msg.setInfo("用户名不得超过20位字符");
msg.setInfo("用户名不得超过30位字符");
return msg;
}
if(!username.matches (regex)){
//用户名格式不正确
msg.setCode("110403");
msg.setInfo("用户名不得含有特殊字符");
return msg;
}
if (subject.hasRole("admin")) {
@@ -436,10 +440,11 @@ public class AdminController {
user.setEmail(email);
}
}
user.setPassword(Base64Encryption.encryptBASE64(password.getBytes()));
user.setPassword(Base64.getEncoder().encodeToString(password.getBytes()));
user.setUid(u.getUid());
} else {
user.setPassword(Base64Encryption.encryptBASE64(password.getBytes()));
user.setPassword(Base64.getEncoder().encodeToString(password.getBytes()));
user.setUid(u.getUid());
}
userService.change(user);
@@ -459,6 +464,7 @@ public class AdminController {
JSONObject jsonObj = JSONObject.parseObject(data);
String images = jsonObj.getString("images");
String uuid = jsonObj.getString("uuid");
Boolean forceDel = jsonObj.getBoolean("forceDel")==null?false:jsonObj.getBoolean("forceDel");
if (images == null) {
msg.setCode("404");
msg.setInfo("为获取到图像信息");
@@ -491,7 +497,7 @@ public class AdminController {
if (imgIds.size() == 0) {
msg.setCode("110404");
} else {
deleimages.dele(uuid, imgIds.stream().toArray(Long[]::new));
deleimages.dele(forceDel,uuid, imgIds.stream().toArray(Long[]::new));
msg.setCode("200");
}
return msg;
@@ -4,7 +4,9 @@ import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.*;
import cn.hellohao.utils.NewSendEmail;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.SetFiles;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@@ -19,6 +21,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
@Controller
@@ -42,6 +47,22 @@ public class AdminRootController {
private ImgreviewService imgreviewService;
@Autowired
private AppClientService appClientService;
@Autowired
private NOSImageupload nOSImageupload;
@Autowired
private OSSImageupload ossImageupload;
@Autowired
private USSImageupload ussImageupload;
@Autowired
private KODOImageupload kodoImageupload;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private FtpServiceImpl ftpService;
@Autowired
private S3Imageupload s3Imageupload;
@Autowired
private WebDAVImageupload webDAVImageupload;
@PostMapping(value = "/getUserList")
@@ -184,19 +205,21 @@ public class AdminRootController {
Keys key = keysService.selectKeys(keyId);
Integer ret = 0;
if (key.getStorageType() == 1) {
ret = NOSImageupload.Initialize(key);
ret = nOSImageupload.Initialize(key);
} else if (key.getStorageType() == 2) {
ret = OSSImageupload.Initialize(key);
ret = ossImageupload.Initialize(key);
} else if (key.getStorageType() == 3) {
ret = USSImageupload.Initialize(key);
ret = ussImageupload.Initialize(key);
} else if (key.getStorageType() == 4) {
ret = KODOImageupload.Initialize(key);
ret = kodoImageupload.Initialize(key);
} else if (key.getStorageType() == 6) {
ret = COSImageupload.Initialize(key);
ret = cosImageupload.Initialize(key);
} else if (key.getStorageType() == 7) {
ret = FtpServiceImpl.Initialize(key);
ret = ftpService.Initialize(key);
} else if (key.getStorageType() == 8) {
ret = S3Imageupload.Initialize(key);
ret = s3Imageupload.Initialize(key);
}else if (key.getStorageType() == 9) {
ret = webDAVImageupload.Initialize(key);
}
Long l = imgService.getsourcememory(keyId);
jsonObject.put("isok", ret);
@@ -219,23 +242,6 @@ 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);
Keys keys = JSON.toJavaObject(jsonObj,Keys.class);
Msg msg = keysService.updateKey(keys);
return msg;
@@ -392,5 +398,50 @@ public class AdminRootController {
return msg;
}
@PostMapping("/sysVersion")
@ResponseBody
public Msg sysupdate(@RequestParam(value = "data", defaultValue = "") String data) {
final Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data);
String dates = jsonObj.getString("dates");
HashMap<String, Object> paramMap = new HashMap<>();
String urls = "http://check.hellohao.cn:8090/getNoticeText";
JSONObject jsonObject =null;
try {
URL u = new URL(urls);
HttpURLConnection uConnection = (HttpURLConnection) u.openConnection();
uConnection.connect();
if(uConnection.getResponseCode()==200){
jsonObject =JSONObject.parseObject(HttpUtil.get(urls));
String openv = jsonObject.getString("openv");
String opentext = jsonObject.getString("opentext");
JSONObject versionJson = new JSONObject();
if(Double.valueOf(openv)>Double.valueOf(dates)){
versionJson.put("code","110200");
versionJson.put("newVersion",openv);
versionJson.put("versionMsg",opentext);
msg.setCode("110200");
msg.setData(versionJson);
}else{
versionJson.put("code","110300");
versionJson.put("newVersion",openv);
versionJson.put("versionMsg","当前已是最新版本");
msg.setCode("110300");
msg.setData(versionJson);
}
}else{
msg.setCode("110500");
msg.setData("未获取到更新状态");
}
uConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
Print.warning("connect failed");
msg.setCode("110500");
msg.setData("未获取到更新状态");
}
return msg;
}
}
@@ -5,6 +5,7 @@ import cn.hellohao.config.GlobalConstant;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.UploadServicel;
import cn.hellohao.service.impl.WebDAVImageupload;
import cn.hellohao.service.impl.deleImages;
import cn.hellohao.utils.GetIPS;
import cn.hellohao.utils.MyVersion;
@@ -19,6 +20,8 @@ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@@ -43,11 +46,12 @@ public class IndexController {
@Autowired private deleImages deleimages;
@Autowired private IRedisService iRedisService;
@Autowired private AppClientService appClientService;
@Autowired private WebDAVImageupload webDAVImageupload;
public static String version = "20240319";
@RequestMapping(value = "/")
public String Welcome(Model model, HttpServletRequest httpServletRequest) {
model.addAttribute("name", "服务端程序(开源版)");
model.addAttribute("version", "20230320");
model.addAttribute("version", version);
model.addAttribute("ip", GetIPS.getIpAddr(httpServletRequest));
model.addAttribute("links", "https://github.com/Hello-hao/tbed");
return "welcome";
@@ -64,6 +68,8 @@ public class IndexController {
JSONObject jsonObject = new JSONObject();
AppClient appClient = appClientService.getAppClientData("app");
jsonObject.put("webname", cd.getString("webname"));
jsonObject.put("systype","free");
jsonObject.put("version",version);
jsonObject.put("websubtitle", cd.getString("websubtitle"));
jsonObject.put("keywords", cd.getString("keywords"));
jsonObject.put("webms", cd.getString("webms"));
@@ -79,10 +85,11 @@ public class IndexController {
jsonObject.put("clientname", appClient.getAppname());
jsonObject.put("clientlogo", appClient.getApplogo());
jsonObject.put("appupdate", appClient.getAppupdate());
jsonObject.put("serverVersion",version);
msg.setData(jsonObject);
return msg;
}
@PostMapping("/uploadChunkFile")
@PostMapping(value = {"/uploadChunkFile","/client/uploadChunkFile"})
@ResponseBody
@CrossOrigin
public Msg uploadChunk(HttpServletRequest request,Chunk chunk) {
@@ -105,7 +112,7 @@ public class IndexController {
}
}
@PostMapping("/processFile")
@PostMapping(value = {"/processFile","/client/processFile"})
@ResponseBody
@CrossOrigin
public Msg processFile(HttpServletRequest request,@RequestParam(value = "data", defaultValue = "") String data){
@@ -146,6 +153,7 @@ public class IndexController {
JSONObject jsonObj = JSONObject.parseObject(data);
Integer setday = jsonObj.getInteger("day");
String imgUrl = jsonObj.getString("imgUrl");
String referer = jsonObj.getString("referer");
String[] URLArr = imgUrl.split("\n");
Subject subject = SecurityUtils.getSubject();
@@ -165,7 +173,10 @@ public class IndexController {
for (int i = 0; i < URLArr.length; i++) {
int temp = i + 1;
if (syscounts >= temp) {
Msg msg = uploadServicel.uploadForLoc(request, null,"URL转存图像", setday, URLArr[i],null);
JSONObject imgJson = new JSONObject();
imgJson.put("imgUrl",URLArr[i]);
imgJson.put("referer",referer);
Msg msg = uploadServicel.uploadForLoc(request, null,"URL转存图像", setday, imgJson,null);
if (!msg.getCode().equals("200")) {
errcounts++;
} else {
@@ -183,6 +194,14 @@ public class IndexController {
return retMsg;
}
//webdav本地托管
@GetMapping("/w/{shortuuid}")
public ResponseEntity<InputStreamResource> getNextcloudImage(HttpServletRequest request, @PathVariable("shortuuid") String shortuuid) {
ResponseEntity<InputStreamResource> webDAV = webDAVImageupload.getWebDAV(shortuuid);
return webDAV;
}
@RequestMapping(value = "/getUploadInfo")
@ResponseBody
public Msg getUploadInfo() {
@@ -316,6 +335,29 @@ public class IndexController {
}
}
@PostMapping(value = {"/verifyCodeFortowSendEmail","/wechat/verifyCodeFortowSendEmail"})
@ResponseBody
public Msg verifyCodeFortowSendEmail() {
Msg msg = new Msg();
try {
ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(90, 35, 2, 2);
// 自定义验证码内容为四则运算方式
captcha.setGenerator(new MathGenerator(1));
String code = getVerifyCodeOperator(captcha.getCode());
String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
iRedisService.setValue("verifyCodeFortowSendEmail_"+uid,code);
JSONObject jsonObject = new JSONObject();
jsonObject.put("codeKey",uid);
jsonObject.put("codeImg",captcha.getImageBase64());
msg.setData(jsonObject);
return msg;
} catch (Exception e) {
e.printStackTrace();
msg.setCode("500");
return msg;
}
}
public static String getVerifyCodeOperator(String str) {
int a = Integer.valueOf(str.substring(0, 1));
String yxf = str.substring(1, 2);
@@ -353,7 +395,7 @@ public class IndexController {
return msg;
}
}
msg = deleimages.dele(null, image.getId());
msg = deleimages.dele(false,null, image.getId());
List<Long> Delids = (List<Long>) msg.getData();
if (!Delids.contains(image.getId())) {
msg.setCode("500");
@@ -5,7 +5,6 @@ import cn.hellohao.auth.token.JWTUtil;
import cn.hellohao.config.SysName;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.utils.Base64Encryption;
import cn.hellohao.utils.NewSendEmail;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.SetText;
@@ -16,6 +15,8 @@ import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
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.Controller;
import org.springframework.ui.Model;
@@ -25,6 +26,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
@@ -44,6 +46,7 @@ public class UserController {
private SysConfigService sysConfigService;
@Autowired
IRedisService iRedisService;
private Logger logger = LoggerFactory.getLogger(UserController.class);
@PostMapping("/register")
@ResponseBody
@@ -52,7 +55,7 @@ public class UserController {
JSONObject jsonObj = JSONObject.parseObject(data);
String username = jsonObj.getString("username");
String email = jsonObj.getString("email");
String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes());
String password = Base64.getEncoder().encodeToString(jsonObj.getString("password").getBytes());
String verifyCodeForRegister = jsonObj.getString("verifyCode");
Object redis_verifyCodeForRegister = iRedisService.getValue("verifyCodeForRegister_"+httpServletRequest.getHeader("verifyCodeForRegister"));
if(!SetText.checkEmail(email)){
@@ -62,10 +65,16 @@ public class UserController {
return msg;
}
String regex = "^\\w+$";
if(username.length()>20 || !username.matches (regex)){
if(username.length()>30){
//用户名格式不正确
msg.setCode("110403");
msg.setInfo("用户名不得超过20位字符");
msg.setInfo("用户名不得超过30位字符");
return msg;
}
if(!username.matches (regex)){
//用户名格式不正确
msg.setCode("110403");
msg.setInfo("用户名不得含有特殊字符");
return msg;
}
if(null==redis_verifyCodeForRegister){
@@ -137,13 +146,64 @@ public class UserController {
return msg;
}
@PostMapping(value = {"/validateEmail","/wechat/validateEmail"})
@ResponseBody
public Msg validateEmail(HttpServletRequest httpServletRequest,@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg();
try {
JSONObject jsonObj = JSONObject.parseObject(data);
String email = jsonObj.getString("email");
String towSendEmailCode = jsonObj.getString("towSendEmailCode");
Object verifyCodeFortowSendEmail =iRedisService.getValue("verifyCodeFortowSendEmail_"+httpServletRequest.getHeader("verifyCodeFortowSendEmail"));
User u = new User();
u.setEmail(email);
User user = userService.getUsers(u);
if(user.getIsok()!=0){
msg.setInfo("不知细叶谁裁出,二月春风似剪刀");
return msg;
}
if(null==verifyCodeFortowSendEmail){
msg.setCode("4035");
msg.setInfo("验证码已失效,请重新弄获取。");
return msg;
}else if(null==towSendEmailCode){
msg.setCode("4036");
msg.setInfo("验证码不能为空。");
return msg;
}
if((verifyCodeFortowSendEmail.toString().toLowerCase()).compareTo((towSendEmailCode.toLowerCase()))==0){
//注册完发激活链接
final Confdata dataJson = confdataService.selectConfdata("config");
JSONObject confdata = JSONObject.parseObject(dataJson.getJsondata());
EmailConfig emailConfig = emailConfigService.getemail();
Thread thread = new Thread() {
public void run() {
Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),confdata);
}
};
thread.start();
msg.setInfo("邮件已发送,请注意查收邮箱尽快激活账户(如果没收到,请检查垃圾邮件)");
}else{
msg.setCode("110408");
msg.setInfo("验证码不正确");
return msg;
}
}catch (Exception e){
logger.error("报错位置:/validateEmail",e);
msg.setCode("500");
msg.setInfo("邮件发送失败");
}
return msg;
}
@PostMapping("/login")//new
@ResponseBody
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 password = Base64.getEncoder().encodeToString(jsonObj.getString("password").getBytes());
String verifyCode = jsonObj.getString("verifyCode");
if(null == email || null == password || null == verifyCode){
msg.setCode("5000");
@@ -178,7 +238,8 @@ public class UserController {
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user.getIsok()==0){
msg.setInfo("你的账号暂未激活");
msg.setCode("110403");
msg.setData(user.getEmail());
msg.setCode("110402");
return msg;
}
if(user.getIsok()<0){
@@ -198,15 +259,15 @@ public class UserController {
} catch (UnknownAccountException e) {
//此异常说明用户名不存在
msg.setCode("4000");
msg.setInfo("登录邮箱不存在");
System.err.println("邮箱不存在");
e.printStackTrace();
msg.setInfo("登录账号不存在");
System.err.println("邮箱/用户名不存在");
// e.printStackTrace();
return msg;
}catch (IncorrectCredentialsException e) {
msg.setCode("4000");
msg.setInfo("登录密码错误");
System.err.println("密码不存在");
e.printStackTrace();
// e.printStackTrace();
return msg;
}catch (Exception e) {
msg.setCode("5000");
@@ -324,7 +385,7 @@ public class UserController {
User user = userService.getUsers(u2);
user.setIsok(1);
String new_pass = HexUtil.decodeHexStr(cip);//解密密码
user.setPassword(Base64Encryption.encryptBASE64(new_pass.getBytes()));
user.setPassword(Base64.getEncoder().encodeToString(new_pass.getBytes()));
String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
user.setUid(uid);
if (user != null) {
@@ -9,13 +9,9 @@ import java.util.List;
@Mapper
public interface CodeMapper {
//查询扩容码
List<Code> selectCode(@Param("code") String code);
Code selectCodekey(@Param("code") String code);
//Integer selectCodekey(@Param("value") String value);
//添加
Integer addCode(Code code);
//删除扩容码
Integer deleteCode(@Param("code") String code);
}
@@ -22,6 +22,10 @@ public interface ImgMapper {
Images selectByPrimaryKey(@Param("id") Long id);
Images selectImgByBrieflink(@Param("brieflink") String brieflink);
Images selectImgByShortlink(@Param("shortlink") String shortlink);
Integer counts(@Param("userid") Integer userid);
Integer setImg(Images images);
@@ -9,11 +9,9 @@ import java.util.List;
@Mapper
public interface KeysMapper {
//查询密钥
Keys selectKeys(@Param("id") Integer id);
List<Keys> getStorageName();
List<Keys> getStorage();
//修改key
Integer updateKey(Keys key);
List<Keys> getKeys();
+6 -322
View File
@@ -1,8 +1,9 @@
package cn.hellohao.pojo;
public class Images {
// 默认的时间字符串格式
import lombok.Data;
@Data
public class Images {
//id, imgname, imgurl, userid
private Long id;
private String imgname;
@@ -38,326 +39,9 @@ public class Images {
private String idname;
private Integer isRepeat;//如果没有开启查重的时候他是0,开启为1
private String searchname;
public Images() {
super();
}
public Images(String imgurl, String sizes, String abnormal, String updatetime, String username, String md5key, String imguid) {
this.imgurl = imgurl;
this.sizes = sizes;
this.abnormal = abnormal;
this.updatetime = updatetime;
this.username = username;
this.md5key = md5key;
this.imguid = imguid;
}
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,
String format,String about,Integer great,String[] classifuidlist,String classificationuid,String violation,
String idname,Integer isRepeat,String searchname) {
this.id = id;
this.imgname = imgname;
this.imgurl = imgurl;
this.userid = userid;
this.sizes = sizes;
this.abnormal = abnormal;
this.source = source;
this.imgtype = imgtype;
this.updatetime = updatetime;
this.username = username;
this.storageType = storageType;
this.starttime = starttime;
this.stoptime = stoptime;
this.explains = explains;
this.md5key = md5key;
this.notes = notes;
this.useridlist = useridlist;
this.imguid = imguid;
this.albumtitle = albumtitle;
this.password = password;
this.selecttype = selecttype;
this.countNum = countNum;
this.monthNum = monthNum;
this.yyyy = yyyy;
this.format = format;
this.about = about;
this.great = great;
this.classifuidlist = classifuidlist;
this.classificationuid = classificationuid;
this.violation = violation;
this.idname = idname;
this.isRepeat = isRepeat;
this.searchname = searchname;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getImgname() {
return imgname;
}
public void setImgname(String imgname) {
this.imgname = imgname;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getSizes() {
return sizes;
}
public void setSizes(String sizes) {
this.sizes = sizes;
}
public String getAbnormal() {
return abnormal;
}
public void setAbnormal(String abnormal) {
this.abnormal = abnormal;
}
public Integer getSource() {
return source;
}
public void setSource(Integer source) {
this.source = source;
}
public Integer getImgtype() {
return imgtype;
}
public void setImgtype(Integer imgtype) {
this.imgtype = imgtype;
}
public String getUpdatetime() {
return updatetime;
}
public void setUpdatetime(String updatetime) {
this.updatetime = updatetime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getStorageType() {
return storageType;
}
public void setStorageType(Integer storageType) {
this.storageType = storageType;
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String starttime) {
this.starttime = starttime;
}
public String getStoptime() {
return stoptime;
}
public void setStoptime(String stoptime) {
this.stoptime = stoptime;
}
public String getExplains() {
return explains;
}
public void setExplains(String explains) {
this.explains = explains;
}
public String getMd5key() {
return md5key;
}
public void setMd5key(String md5key) {
this.md5key = md5key;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getUseridlist() {
return useridlist;
}
public void setUseridlist(String useridlist) {
this.useridlist = useridlist;
}
public String getImguid() {
return imguid;
}
public void setImguid(String imguid) {
this.imguid = imguid;
}
public String getAlbumtitle() {
return albumtitle;
}
public void setAlbumtitle(String albumtitle) {
this.albumtitle = albumtitle;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getSelecttype() {
return selecttype;
}
public void setSelecttype(Integer selecttype) {
this.selecttype = selecttype;
}
public Long getCountNum() {
return countNum;
}
public void setCountNum(Long countNum) {
this.countNum = countNum;
}
public Integer getMonthNum() {
return monthNum;
}
public void setMonthNum(Integer monthNum) {
this.monthNum = monthNum;
}
public String getYyyy() {
return yyyy;
}
public void setYyyy(String yyyy) {
this.yyyy = yyyy;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public Integer getGreat() {
return great;
}
public void setGreat(Integer great) {
this.great = great;
}
public String[] getClassifuidlist() {
return classifuidlist;
}
public void setClassifuidlist(String[] classifuidlist ) {
this.classifuidlist = classifuidlist;
}
public String getClassificationuid() {
return classificationuid;
}
public void setClassificationuid(String classificationuid) {
this.classificationuid = classificationuid;
}
public String getViolation() {
return violation;
}
public void setViolation(String violation) {
this.violation = violation;
}
public String getIdname() {
return idname;
}
public void setIdname(String idname) {
this.idname = idname;
}
public Integer getIsRepeat() {
return isRepeat;
}
public void setIsRepeat(Integer isRepeat) {
this.isRepeat = isRepeat;
}
public String getSearchname() {
return searchname;
}
public void setSearchname(String searchname) {
this.searchname = searchname;
}
private String brieflink;
private String shortlink;
private String order;
}
+4
View File
@@ -14,5 +14,9 @@ public class Keys {
private Integer storageType;
private String keyname;
private String RootPath;//存入的目录
private Boolean SysTransmit;
public Boolean getSysTransmit() {
return SysTransmit==null?false:SysTransmit;
}
}
-4
View File
@@ -11,16 +11,12 @@ public class Msg implements Serializable {
private static final long serialVersionUID = 5196249482551119279L;
//返回码
private String code ="200";
//提示信息
private String info="操作成功";
//返回数据
private Object data;
//异常
private String exceptions;
@@ -34,6 +34,8 @@ public class FirstJob {
@Autowired
private S3Imageupload s3Imageupload;
@Autowired
private WebDAVImageupload webDAVImageupload;
@Autowired
private FtpServiceImpl ftpService;
@Autowired
ImgTempService imgTempService;
@@ -78,6 +80,8 @@ public class FirstJob {
firstJob.ftpService.delFTP(keys.getId(), images);
}else if(keys.getStorageType()==8){
firstJob.s3Imageupload.deleS3(keys.getId(), images);
}else if(keys.getStorageType()==9){
firstJob.webDAVImageupload.delWebDAV(keys.getId(), images);
}else{
System.err.println("未获取到对象存储参数,上传失败。");
}
@@ -3,6 +3,7 @@ package cn.hellohao.service;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -21,6 +22,10 @@ public interface ImgService {
Images selectByPrimaryKey(Long id);
Images selectImgByBrieflink(String brieflink);
Images selectImgByShortlink(String shortlink);
Integer counts(Integer userid);
Integer setImg(Images images);
@@ -15,13 +15,17 @@ import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
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.io.FileInputStream;
import java.util.Map;
@Service
public class COSImageupload {
private static Logger logger = LoggerFactory.getLogger(COSImageupload.class);
static COSClient cosClient;
static Keys key;
@@ -29,16 +33,18 @@ public class COSImageupload {
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
File file = null;
FileInputStream stream = 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();
stream = new FileInputStream(file);
try {
String bucketName = key.getBucketname();
String userkey = username + "/" + ShortUIDName + "." + prefix;
PutObjectRequest putObjectRequest =
new PutObjectRequest(bucketName, userkey, file);
new PutObjectRequest(bucketName, userkey, stream,null);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
} catch (CosServiceException serverException) {
returnImage.setCode("400");
@@ -47,10 +53,12 @@ public class COSImageupload {
returnImage.setCode("400");
clientException.printStackTrace();
}
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
logger.error("COS协议上传时发生异常:",e);
returnImage.setCode("500");
}
return returnImage;
@@ -11,6 +11,8 @@ import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -28,10 +30,8 @@ import java.util.*;
@Service
public class ClientService {
private static Logger logger = LoggerFactory.getLogger(ClientService.class);
@Autowired
ConfdataService confdataService;
@Autowired
SysConfigService sysConfigService;
@Autowired private ConfdataService confdataService;
@Autowired private SysConfigService sysConfigService;
@Autowired private UserMapper userMapper;
@Autowired private KeysMapper keysMapper;
@Autowired private UploadConfigMapper uploadConfigMapper;
@@ -60,31 +60,70 @@ public class ClientService {
}
imageFileName = multipartFile.getOriginalFilename();
File file = SetFiles.changeFile_new(multipartFile);
FileInputStream stream = new FileInputStream(file);
User u2 = new User();
if (!file.exists() || email == null || pass == null) {
msg.setCode("4005");
msg.setInfo("必要参数不能为空");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
if (uploadConfig.getBlacklist() != null) {
String[] iparr = uploadConfig.getBlacklist().split(";");
for (String s : iparr) {
if (s.equals(userip)) {
msg.setCode("4010");
msg.setInfo("你暂时不能上传");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
}
}
u2.setEmail(email);
u2.setPassword(Base64Encryption.encryptBASE64(pass.getBytes()));
u2.setPassword(Base64.getEncoder().encodeToString(pass.getBytes()));
User u = userMapper.getUsers(u2);
if (null == u || u.getIsok() != 1) {
msg.setCode("4006");
msg.setInfo("用户信息不正确,账号异常");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
String imguid = UUID.randomUUID().toString().replace("-", "");
Msg msg1 = updateImgCheck(u, uploadConfig);
if (!msg1.getCode().equals("300")) {
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg1;
}
JSONObject updateJson = JSONObject.parseObject(msg1.getData().toString());
final JSONObject groupJson = updateJson.getJSONObject("group");
final Group group = groupJson.toJavaObject(Group.class);
Long memory = updateJson.getLong("memory");
Long UsedTotleMemory = updateJson.getLong("UsedTotleMemory");
Long TotleMemory = updateJson.getLong("TotleMemory");
String updatePath = updateJson.getString("updatePath");
sourceKeyId = group.getKeyid();
Keys key = keysMapper.selectKeys(sourceKeyId);
Long tmp = (memory == -1 ? -2 : UsedTotleMemory);
if (tmp >= memory) {
msg.setCode("4007");
msg.setInfo(u == null ? "游客空间已用尽" : "您的可用空间不足");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
if (file.length() > TotleMemory) {
@@ -92,63 +131,67 @@ public class ClientService {
System.err.println("最大限制:" + TotleMemory);
msg.setCode("4008");
msg.setInfo("图像超出系统限制大小");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
md5key = DigestUtils.md5Hex(fis);
} catch (Exception e) {
e.printStackTrace();
System.out.println("未获取到图片的MD5,成成UUID");
}finally{
try {
if (null != fis)
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Msg fileMiME = TypeDict.FileMiME(file);
md5key = DigestUtils.md5Hex(stream);
// FileInputStream fis = null;
// try {
// fis = new FileInputStream(file);
// md5key = DigestUtils.md5Hex(fis);
// } catch (Exception e) {
// logger.error("未获取到图片的MD5,成成UUID异常:",e);
// }finally{
// try {
// if (null != fis)
// fis.close();
// } catch (Exception e) {
// logger.error("ClientService-110异常",e);
// }
// }
Msg fileMiME = TypeDict.FileMiME(stream);
if (!fileMiME.getCode().equals("200")) {
msg.setCode("4009");
msg.setInfo(fileMiME.getInfo());
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
if (md5key == null || md5key.equals("")) {
md5key = UUID.randomUUID().toString().replace("-", "");
}
String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
if (uploadConfig.getBlacklist() != null) {
String[] iparr = uploadConfig.getBlacklist().split(";");
for (String s : iparr) {
if (s.equals(userip)) {
msg.setCode("4010");
msg.setInfo("你暂时不能上传");
return msg;
}
}
}
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
Images imgObj = new Images();
String imgnameEd = null;
Map<Map<String, String>, File> map = new HashMap<>();
String shortUuid_y = SetText.getShortUuid();
String shortUuid_s = SetText.getShortUuid();
if (file.exists()) {
Map<String, String> m1 = new HashMap<>();
String shortUuid_y = SetText.getShortUuid();
m1.put("prefix", prefix);
m1.put("name", shortUuid_y);
map.put(m1, file);
imgnameEd = updatePath + "/" + shortUuid_y + "." + prefix;
imgObj.setImgname(imgnameEd);
if (key.getStorageType().equals(5)) {
imgObj.setImgurl(key.getRequestAddress() + "/ota/" + imgnameEd);
} else {
imgObj.setImgurl(confdata.getString("domain") + "/ota/" + imgnameEd);
} else if(key.getStorageType().equals(9) && key.getSysTransmit()){
imgObj.setImgurl(confdata.getString("domain") + "/w/" + shortUuid_y);
}else {
imgObj.setImgurl(key.getRequestAddress() + "/" + imgnameEd);
}
imgObj.setSizes(Long.toString(file.length()));
}else{
msg.setInfo("未获取到指定图像:110503");
msg.setCode("110503");
file.delete();
return msg;
}
imgObj.setUpdatetime(df.format(new Date()));
@@ -167,9 +210,12 @@ public class ClientService {
imgObj.setMd5key(md5key);
imgObj.setImguid(imguid);
imgObj.setFormat(fileMiME.getData().toString());
imgObj.setShortlink(shortUuid_y);
imgObj.setBrieflink(shortUuid_s);
imgObj.setIdname(imageFileName);
Msg insertRet = imgServiceImpl.insertImgDataForCheck(imgObj,u,confdata,file.getName());
if (insertRet.getCode().equals("000")) {
file.delete();
return insertRet;
}
long stime = System.currentTimeMillis();
@@ -185,43 +231,48 @@ public class ClientService {
imgServiceImpl.deleimgForImgUid(imgObj.getImguid());
msg.setCode("5001");
msg.setInfo("上传服务内部错误");
file.delete();
return msg;
}
file.delete();
msg.setData(jsonObject);
return msg;
} catch (Exception e) {
e.printStackTrace();
msg.setCode("5001");
msg.setInfo("Error for server:500");
logger.error("ClientServiceError for server-202行异常",e);
return msg;
}
}
public static Group group;
public static Long memory;
public static Long TotleMemory;
public static Long UsedTotleMemory;
public static String updatePath = "tourist";
// public static Group group;
// public static Long memory;
// public static Long TotleMemory;
// public static Long UsedTotleMemory;
// public static String updatePath = "tourist";
private Msg updateImgCheck(User user, UploadConfig uploadConfig) {
Msg msg = new Msg();
java.text.DateFormat dateFormat = null;
JSONObject jsonObject = new JSONObject();
String updatePath = "tourist";
try {
dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Group group = GetCurrentSource.GetSource(user == null ? null : user.getId());
jsonObject.put("group",group);
if (user == null) {
if (uploadConfig.getIsupdate() != 1) {
msg.setCode("1000");
msg.setInfo("系统已禁用游客上传");
return msg;
}
group = GetCurrentSource.GetSource(null);
memory = Long.valueOf(uploadConfig.getVisitormemory()); // 单位 B 游客设置总量
TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists()); // 单位 B 游客单文件大小
UsedTotleMemory =
Long memory = Long.valueOf(uploadConfig.getVisitormemory()); // 单位 B 游客设置总量
Long TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists()); // 单位 B 游客单文件大小
Long UsedTotleMemory =
imgServiceImpl.getusermemory(0) == null
? 0L
: imgServiceImpl.getusermemory(0); // 单位 B
jsonObject.put("memory",memory);
jsonObject.put("TotleMemory",TotleMemory);
jsonObject.put("UsedTotleMemory",UsedTotleMemory);
} else {
// 判断用户能不能上传
if (uploadConfig.getUserclose() != 1) {
@@ -230,21 +281,24 @@ public class ClientService {
return msg;
}
updatePath = user.getUsername();
group = GetCurrentSource.GetSource(user.getId());
memory = Long.valueOf(user.getMemory()); // 单位 B
TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser()); // 单位 B
UsedTotleMemory =
Long memory = Long.valueOf(user.getMemory()); // 单位 B
Long TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser()); // 单位 B
Long UsedTotleMemory =
imgServiceImpl.getusermemory(user.getId()) == null
? 0L
: imgServiceImpl.getusermemory(user.getId()); // 单位 B
jsonObject.put("memory",memory);
jsonObject.put("TotleMemory",TotleMemory);
jsonObject.put("UsedTotleMemory",UsedTotleMemory);
}
// 判断上传的图片目录结构类型
if (uploadConfig.getUrltype() == 2) {
updatePath = dateFormat.format(new Date());
jsonObject.put("updatePath",updatePath);
msg.setData(jsonObject);
}
msg.setCode("300");
} catch (Exception e) {
e.printStackTrace();
logger.error("ClientService-异常",e);
msg.setCode("500");
}
return msg;
@@ -7,15 +7,19 @@ 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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class FtpServiceImpl {
private static Logger logger = LoggerFactory.getLogger(FtpServiceImpl.class);
private Keys key;
public static int Initialize(Keys k) {
@@ -66,22 +70,26 @@ public class FtpServiceImpl {
return returnImage;
}
File file = null;
FileInputStream stream = 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();
stream = new FileInputStream(file);
boolean isUpload = ftp.upload(
"/" + username,
ShortUIDName + "." + prefix,
file);
stream);
if (!isUpload) {
returnImage.setCode("400");
}
try {if(stream!=null){stream.close();}} catch (Exception e) { }
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
logger.error("FTP发生异常:",e);
returnImage.setCode("500");
}
return returnImage;
@@ -46,6 +46,16 @@ public class ImgServiceImpl implements ImgService {
return imgMapper.selectByPrimaryKey(id);
}
@Override
public Images selectImgByBrieflink(String brieflink) {
return imgMapper.selectImgByBrieflink(brieflink);
}
@Override
public Images selectImgByShortlink(String shortlink) {
return imgMapper.selectImgByShortlink(shortlink);
}
@Override
public Integer counts(Integer userid) {
// TODO Auto-generated method stub
@@ -131,10 +141,9 @@ public class ImgServiceImpl implements ImgService {
if(sysConfig.getCheckduplicate().equals("1")){
//查重
Images img = new Images();
img.setUserid(user.getId());
img.setUserid(user==null?0:user.getId());
img.setMd5key(images.getMd5key());
List<Images> list = imgMapper.selectImgUrlByMD5(img);
jsonObject.put("url", list.get(0).getImgurl());
if (list.size() > 0) {
jsonObject.put("url", list.get(0).getImgurl());
jsonObject.put("name", flilename);
@@ -58,6 +58,8 @@ public class InitializationStorage implements CommandLineRunner {
FtpServiceImpl.Initialize(key);
}else if(key.getStorageType()==8){
S3Imageupload.Initialize(key);
}else if(key.getStorageType()==9){
WebDAVImageupload.Initialize(key);
}
}
}
@@ -5,22 +5,26 @@ import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
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.io.FileInputStream;
import java.util.Map;
@Service
public class KODOImageupload {
private static Logger logger = LoggerFactory.getLogger(KODOImageupload.class);
static String upToken;
static BucketManager bucketManager;
static Keys key;
@@ -28,31 +32,20 @@ public class KODOImageupload {
public ReturnImage ImageuploadKODO(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
Configuration cfg;
if (key.getEndpoint().equals("1")) {
cfg = new Configuration(Zone.zone0());
} else if (key.getEndpoint().equals("2")) {
cfg = new Configuration(Zone.zone1());
} else if (key.getEndpoint().equals("3")) {
cfg = new Configuration(Zone.zone2());
} else if (key.getEndpoint().equals("4")) {
cfg = new Configuration(Zone.zoneNa0());
} else {
cfg = new Configuration(Zone.zoneAs0());
}
Configuration cfg = new Configuration(Region.autoRegion());
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(key.getAccessKey(), key.getAccessSecret());
String upToken = auth.uploadToken(key.getBucketname(), null, 7200, null);
File file = null;
FileInputStream stream = 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();
stream = new FileInputStream(file);
try {
Response response =
uploadManager.put(
file, username + "/" + ShortUIDName + "." + prefix, upToken);
Response response = uploadManager.put(stream,username + "/" + ShortUIDName + "." + prefix, upToken, null, null);
DefaultPutRet putRet =
new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
@@ -65,10 +58,12 @@ public class KODOImageupload {
} catch (QiniuException ex2) {
}
}
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
logger.error("KODO发生异常:",e);
returnImage.setCode("500");
}
return returnImage;
@@ -76,41 +71,25 @@ public class KODOImageupload {
public static Integer Initialize(Keys k) {
int ret = -1;
if (org.apache.commons.lang3.StringUtils.isBlank(k.getAccessKey())
|| org.apache.commons.lang3.StringUtils.isBlank(k.getAccessSecret())
|| org.apache.commons.lang3.StringUtils.isBlank(k.getEndpoint())
|| org.apache.commons.lang3.StringUtils.isBlank(k.getBucketname())
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getBucketname())
|| StringUtils.isBlank(k.getRequestAddress())) {
return -1;
}
Configuration cfg;
if (k.getEndpoint().equals("1")) {
cfg = new Configuration(Zone.zone0());
} else if (k.getEndpoint().equals("2")) {
cfg = new Configuration(Zone.zone1());
} else if (k.getEndpoint().equals("3")) {
cfg = new Configuration(Zone.zone2());
} else if (k.getEndpoint().equals("4")) {
cfg = new Configuration(Zone.zoneNa0());
} else {
cfg = new Configuration(Zone.zoneAs0());
}
Configuration cfg = new Configuration(Region.autoRegion());
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret());
String upToken =
auth.uploadToken(
k.getBucketname(),
null,
7200,
null); // auth.uploadToken(k.getBucketname());
BucketManager bmObj = new BucketManager(auth, cfg);
String upToken = auth.uploadToken(k.getBucketname(), null, 7200, null);
BucketManager BM = new BucketManager(auth, cfg);
BucketManager.FileListIterator fileListIterator = null;
try {
fileListIterator = bmObj.createFileListIterator(k.getBucketname(), "", 1, "/");
fileListIterator = BM.createFileListIterator(k.getBucketname(), "", 1, "/");
FileInfo[] items = fileListIterator.next();
if (items != null) {
ret = 1;
bucketManager = bmObj;
bucketManager = BM;
key = k;
}
} catch (Exception e) {
@@ -2,6 +2,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Msg;
import cn.hellohao.utils.Print;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -30,6 +31,8 @@ public class KeysServiceImpl implements KeysService {
private FtpServiceImpl ftpService;
@Autowired
private S3Imageupload s3Imageupload;
@Autowired
private WebDAVImageupload webDAVImageupload;
@Override
@@ -51,6 +54,29 @@ public class KeysServiceImpl implements KeysService {
public Msg updateKey(Keys key) {
Msg msg = new Msg();
Integer ret = -2;
//修正一边数据格式,去除末尾的斜杠
if(key.getStorageType()==9 || key.getStorageType()==8){
//s3或者webdav
if(!StringUtils.isBlank(key.getRootPath()) && !key.getRootPath().equals("/")){
if (key.getRootPath().endsWith("/")) {
String rootpath = key.getRootPath();
key.setRootPath(rootpath.substring(0, rootpath.length() - 1));
}
}
}
if(!StringUtils.isBlank(key.getEndpoint())){
final String endpoint = key.getEndpoint();
if (endpoint.endsWith("/")) {
key.setEndpoint(endpoint.substring(0, endpoint.length() - 1));
}
}
if(!StringUtils.isBlank(key.getRequestAddress())){
final String requestAddress = key.getRequestAddress();
if (requestAddress.endsWith("/")) {
key.setRequestAddress(requestAddress.substring(0, requestAddress.length() - 1));
}
}
if(key.getStorageType()==1){
ret =nOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){
@@ -67,6 +93,8 @@ public class KeysServiceImpl implements KeysService {
ret = ftpService.Initialize(key);
}else if(key.getStorageType()==8){
ret = s3Imageupload.Initialize(key);
}else if(key.getStorageType()==9){
ret = webDAVImageupload.Initialize(key);
}else{
Print.Normal("为获取到存储参数,或者使用存储源是本地的。");
}
@@ -9,6 +9,8 @@ import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.ObjectListing;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
@@ -11,13 +11,17 @@ import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.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.io.FileInputStream;
import java.util.Map;
@Service
public class OSSImageupload {
private static Logger logger = LoggerFactory.getLogger(OSSImageupload.class);
static OSS ossClient;
static Keys key;
@@ -25,6 +29,7 @@ public class OSSImageupload {
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
File file = null;
FileInputStream stream = null;
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
try {
@@ -32,19 +37,22 @@ public class OSSImageupload {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
Msg fileMiME = TypeDict.FileMiME(file);
stream = new FileInputStream(file);
Msg fileMiME = TypeDict.FileMiME(stream);
meta.setHeader("content-type", fileMiME.getData().toString());
PutObjectRequest putObjectRequest =
new PutObjectRequest(
key.getBucketname(),
username + "/" + ShortUIDName + "." + prefix,
file,
stream,
meta);
ossClient.putObject(putObjectRequest);
try {if(stream!=null){stream.close();}} catch (Exception e) { }
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
logger.error("OSS上传发生异常:",e);
returnImage.setCode("500");
}
return returnImage;
@@ -12,16 +12,14 @@ 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 com.amazonaws.services.s3.model.*;
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.io.FileInputStream;
import java.util.List;
import java.util.Map;
@@ -51,21 +49,28 @@ public class S3Imageupload {
return returnImage;
}
File file = null;
FileInputStream stream = 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();
stream = new FileInputStream(file);
//解决存储源不能浏览图片的问题
// ObjectMetadata objectMetadata = new ObjectMetadata();
// objectMetadata.addUserMetadata();
AS3.putObject(
new PutObjectRequest(
KEY.getBucketname(),
username + "/" + ShortUIDName + "." + prefix,
file));
stream,null));
// S3Object object = s3.getObject( new GetObjectRequest( key.getBucketname(),
try {if(stream!=null){stream.close();}} catch (Exception e) { }
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
logger.error("S3协议上传发生异常:",e);
returnImage.setCode("500");
}
return returnImage;
@@ -1,102 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.utils.SetText;
import cn.hellohao.utils.TypeDict;
import com.UpYun;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
import java.util.Map;
@Service
public class UFileImageupload1 {
static UpYun uFile;
static Keys key;
/*
* 废弃方法待补位
* */
public ReturnImage ImageuploadUFile(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
File file = null;
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
try {
for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid();
file = entry.getValue();
Msg fileMiME = TypeDict.FileMiME(file);
meta.setHeader("content-type", fileMiME.getData().toString());
uFile.setContentMD5(UpYun.md5(file));
boolean result =
uFile.writeFile(
username + "/" + ShortUID + "." + entry.getKey(), file, true);
if (result) {
returnImage.setImgname(username + "/" + ShortUID + "." + entry.getKey());
returnImage.setImgurl(
key.getRequestAddress()
+ "/"
+ username
+ "/"
+ ShortUID
+ "."
+ entry.getKey());
returnImage.setImgSize(entry.getValue().length());
returnImage.setCode("200");
} else {
returnImage.setCode("400");
System.err.println("上传失败");
}
}
} catch (Exception e) {
returnImage.setCode("500");
}
returnImage.setCode("500");
return returnImage;
}
public static Integer Initialize(Keys k) {
int ret = -1;
if (k.getAccessSecret() != null
&& k.getAccessKey() != null
&& k.getBucketname() != null
&& k.getRequestAddress() != null) {
if (!k.getAccessSecret().equals("")
&& !k.getAccessKey().equals("")
&& !k.getBucketname().equals("")
&& !k.getRequestAddress().equals("")) {
UpYun ufObj = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret());
List<UpYun.FolderItem> items = null;
try {
items = ufObj.readDir("/", null);
ret = 1;
uFile = ufObj;
key = k;
} catch (Exception e) {
System.out.println("UFile Object Is null");
ret = -1;
}
}
}
return ret;
}
public Boolean delUFile(Integer keyID, Images images) {
boolean b = true;
try {
boolean result = uFile.deleteFile(images.getImgname(), null);
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -8,14 +8,18 @@ import cn.hellohao.utils.TypeDict;
import com.UpYun;
import com.aliyun.oss.model.ObjectMetadata;
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.io.FileInputStream;
import java.util.List;
import java.util.Map;
@Service
public class USSImageupload {
private static Logger logger = LoggerFactory.getLogger(USSImageupload.class);
static UpYun upyun;
static Keys key;
@@ -23,6 +27,7 @@ public class USSImageupload {
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
File file = null;
FileInputStream stream = null;
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
try {
@@ -30,21 +35,24 @@ public class USSImageupload {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
Msg fileMiME = TypeDict.FileMiME(file);
stream = new FileInputStream(file);
Msg fileMiME = TypeDict.FileMiME(stream);
meta.setHeader("content-type", fileMiME.getData().toString());
upyun.setContentMD5(UpYun.md5(file));
boolean result =
upyun.writeFile(username + "/" + ShortUIDName + "." + prefix, file, true);
upyun.writeFile(username + "/" + ShortUIDName + "." + prefix, stream, true, null);
if (result) {
} else {
System.err.println("上传失败");
returnImage.setCode("400");
}
try {if(stream!=null){stream.close();}} catch (Exception e) { }
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
try {if(stream!=null){stream.close();}} catch (Exception ex) { }
logger.error("OSS上传发生异常:",e);
returnImage.setCode("500");
}
return returnImage;
@@ -18,12 +18,17 @@ import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
@@ -53,7 +58,7 @@ public class UploadServicel {
File file,
String imgName,
Integer setday,
String imgUrl,
JSONObject imgJson,
String md5key) {
Msg msg = new Msg();
try {
@@ -69,55 +74,31 @@ public class UploadServicel {
u = userMapper.getUsers(u);
}
Integer sourceKeyId = 0;
if (imgUrl != null) {
Msg imgData = uploadForURL(request, imgUrl);
if (imgJson != null) {
Msg imgData = uploadForURL(request, imgJson.getString("imgUrl"),imgJson.getString("referer"));
if (imgData.getCode().equals("200")) {
file = new File((String) imgData.getData());
} else {
return imgData;
}
}
FileInputStream stream = new FileInputStream(file);
String imguid = UUID.randomUUID().toString().replace("-", "");
Msg msg1 = updateImgCheck(u, uploadConfig);
if (!msg1.getCode().equals("300")) {
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg1;
}
sourceKeyId = group.getKeyid();
Keys key = keysMapper.selectKeys(sourceKeyId);
Long tmp = (memory == -1 ? -2 : UsedTotleMemory);
if (tmp >= memory) {
msg.setCode("4005");
msg.setInfo(u == null ? "游客空间已用尽" : "您的可用空间不足");
return msg;
}
if (file.length() > TotleMemory) {
msg.setCode("4006");
msg.setInfo("图像超出系统限制大小");
return msg;
}
Msg fileMiME = TypeDict.FileMiME(file);
if (!fileMiME.getCode().equals("200")) {
msg.setCode("4000");
msg.setInfo(fileMiME.getInfo());
return msg;
}
if (md5key == null || md5key.equals("")) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
md5key = DigestUtils.md5Hex(fis);
} catch (Exception e) {
logger.error("获取MD5错误",e);
}finally{
try {
if (null != fis)
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
JSONObject updateJson = JSONObject.parseObject(msg1.getData().toString());
final JSONObject groupJson = updateJson.getJSONObject("group");
final Group group = groupJson.toJavaObject(Group.class);
Long memory = updateJson.getLong("memory");
Long UsedTotleMemory = updateJson.getLong("UsedTotleMemory");
Long TotleMemory = updateJson.getLong("TotleMemory");
String updatePath = updateJson.getString("updatePath");
if (uploadConfig.getBlacklist() != null) {
String[] iparr = uploadConfig.getBlacklist().split(";");
for (String s : iparr) {
@@ -125,31 +106,96 @@ public class UploadServicel {
file.delete();
msg.setCode("4003");
msg.setInfo("你暂时不能上传");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
}
}
sourceKeyId = group.getKeyid();
Keys key = keysMapper.selectKeys(sourceKeyId);
Long tmp = (memory == -1 ? -2 : UsedTotleMemory);
if (tmp >= memory) {
msg.setCode("4005");
msg.setInfo(u == null ? "游客空间已用尽" : "您的可用空间不足");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
if (file.length() > TotleMemory) {
msg.setCode("4006");
msg.setInfo("图像超出系统限制大小");
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
Msg fileMiME = TypeDict.FileMiME(stream);
if (!fileMiME.getCode().equals("200")) {
msg.setCode("4000");
msg.setInfo(fileMiME.getInfo());
try {
if(stream!=null){stream.close();}
file.delete();
} catch (Exception e) { }
return msg;
}
if (md5key == null || md5key.equals("")) {
md5key = DigestUtils.md5Hex(stream);
// FileInputStream fis = null;
// try {
// fis = new FileInputStream(file);
// md5key = DigestUtils.md5Hex(fis);
// } catch (Exception e) {
// logger.error("获取MD5错误",e);
// }finally{
// try {
// if (null != fis)
// fis.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
try {
if(stream!=null){stream.close();}
} catch (Exception e) { }
// 判断路径格式 处理一下,去掉最前面的/
String RootPath = key.getRootPath().replace(" ", "");
if (!RootPath.equals("/")) {
updatePath = RootPath.substring(1) + "/" + updatePath;
}
// 先存数据库
Images imgObj = new Images();
String imgnameEd = null;
Map<Map<String, String>, File> map = new HashMap<>();
String shortUuid_y = SetText.getShortUuid();
String shortUuid_s = SetText.getShortUuid();
if (file.exists()) {
Map<String, String> m1 = new HashMap<>();
String shortUuid_y = SetText.getShortUuid();
m1.put("prefix", prefix);
m1.put("name", shortUuid_y);
map.put(m1, file);
imgnameEd = updatePath + "/" + shortUuid_y + "." + prefix;
imgObj.setImgname(imgnameEd);
if (key.getStorageType().equals(5)) {
imgObj.setImgurl(key.getRequestAddress() + "/ota/" + imgnameEd);
} else {
imgObj.setImgurl(confdata.getString("domain") + "/ota/" + imgnameEd);
} else if(key.getStorageType().equals(9) && key.getSysTransmit()){
imgObj.setImgurl(confdata.getString("domain") + "/w/" + shortUuid_y);
}else {
imgObj.setImgurl(key.getRequestAddress() + "/" + imgnameEd);
}
imgObj.setSizes(Long.toString(file.length()));
}else{
msg.setInfo("未获取到指定图像:110503");
msg.setCode("110503");
try { file.delete(); } catch (Exception e) { }
return msg;
}
imgObj.setUpdatetime(df.format(new Date()));
@@ -168,14 +214,18 @@ public class UploadServicel {
imgObj.setMd5key(md5key);
imgObj.setImguid(imguid);
imgObj.setFormat(fileMiME.getData().toString());
imgObj.setShortlink(shortUuid_y);
imgObj.setBrieflink(shortUuid_s);
imgObj.setIdname(imgName);
// Integer insertRet = imgMapper.insertImgData(imgObj);
Msg insertRet = imgServiceImpl.insertImgDataForCheck(imgObj,u,confdata,file.getName());
if (insertRet.getCode().equals("000")) {
try { file.delete(); } catch (Exception e) { }
return insertRet;
}
long stime = System.currentTimeMillis();
System.out.println("上传前地址:"+updatePath);
ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
if (returnImage.getCode().equals("200")) {
long etime = System.currentTimeMillis();
@@ -184,24 +234,21 @@ public class UploadServicel {
jsonObject.put("name", imgObj.getImgname());
jsonObject.put("imguid", imgObj.getImguid());
imgViolationJudgeService.LegalImageCheck(imgObj,key);
// new Thread(
// () -> {
// LegalImageCheck(imgObj);
// })
// .start();
} else {
imgServiceImpl.deleimgForImgUid(imgObj.getImguid());
msg.setCode("5001");
msg.setInfo("上传服务内部错误");
try { file.delete(); } catch (Exception e) { }
return msg;
}
file.delete();
msg.setData(jsonObject);
file.delete();
return msg;
} catch (Exception e) {
e.printStackTrace();
msg.setInfo("上传时发生了一些错误");
msg.setCode("110500");
file.delete();
return msg;
}
}
@@ -215,7 +262,6 @@ public class UploadServicel {
String md5 = jsonObj.getString("md5");
String classifications = jsonObj.getString("classifications");
Integer day = jsonObj.getInteger("day");
String source = jsonObj.getString("source");
String imgIdentifier = jsonObj.getString("imgIdentifier");
JSONArray jsonArray = new JSONArray();
classifications = classifications==null?"":classifications;
@@ -254,59 +300,68 @@ public class UploadServicel {
}
public static Msg uploadForURL(HttpServletRequest request, String imgurl) {
Msg msg = new Msg();
if (true) {
Long imgsize = 0L;
try {
if (imgsize == 0) {
String ShortUID = SetText.getShortUuid();
String savePath =
request.getSession().getServletContext().getRealPath("/")
+ File.separator
+ "hellohaotmp"
+ File.separator;
Map<String, Object> bl = ImgUrlUtil.downLoadFromUrl(imgurl, ShortUID, savePath);
if ((Boolean) bl.get("res") == true) {
msg.setCode("200");
msg.setData(bl.get("imgPath"));
return msg;
} else {
if (bl.get("StatusCode").equals("110403")) {
msg.setInfo("该链接非图像文件,无法上传");
} else {
msg.setInfo("该链接暂时无法上传");
}
msg.setCode("500");
}
public static Msg uploadForURL(HttpServletRequest request, String imgurls,String referer) {
final Msg msg = new Msg();
String url = imgurls;
// 先判断是不是有效链接 并且自动判断协议头http(s)://
GetProtocol getProtocol = new GetProtocol();
String protocol = getProtocol.getProtocol(url,referer);
if (protocol == null) {
msg.setInfo("服务器解析该链接失败");
msg.setCode("500");
return msg;
} else {
url = protocol;
}
Long imgsize = 0L;
try {
if (imgsize == 0) {
String ShortUID = SetText.getShortUuid();
String savePath =
request.getSession().getServletContext().getRealPath("/")
+ File.separator
+ "hellohaotmp"
+ File.separator;
Map<String, Object> bl = ImgUrlUtil.downLoadFromUrl(url,referer, ShortUID, savePath);
if ((Boolean) bl.get("res") == true) {
// File file = new File();
msg.setCode("200");
msg.setData(bl.get("imgPath")); // savePath + File.separator + ShortUID
return msg;
} else {
if (bl.get("StatusCode").equals("110403")) {
msg.setInfo("该链接非图像文件,无法上传");
} else {
msg.setInfo("该链接暂时无法上传");
}
msg.setCode("500");
msg.setInfo("获取资源失败");
}
} catch (Exception e) {
} else {
msg.setCode("500");
msg.setInfo("获取资源失败");
}
} else {
} catch (Exception e) {
msg.setCode("500");
msg.setInfo("该链接无效");
msg.setInfo("获取资源失败");
}
return msg;
}
private static Group group; // 上传用户或游客的所属分组
private static Long memory; // 上传用户或者游客的分配容量 memory
private static Long TotleMemory; // 用户或者游客下可使用的总容量 //maxsize
private static Long UsedTotleMemory; // 用户或者游客已经用掉的总容量 //usermemory
private static String updatePath = "tourist";
// private static Group group; // 上传用户或游客的所属分组
// private static Long memory; // 上传用户或者游客的分配容量 memory
// private static Long TotleMemory; // 用户或者游客下可使用的总容量 //maxsize
// private static Long UsedTotleMemory; // 用户或者游客已经用掉的总容量 //usermemory
// private static String updatePath = "tourist";
// 判断用户 或 游客 当前上传图片的一系列校验
private Msg updateImgCheck(User user, UploadConfig uploadConfig) {
Msg msg = new Msg();
java.text.DateFormat dateFormat = null;
JSONObject jsonObject = new JSONObject();
String updatePath = "tourist";
try {
dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Group group = GetCurrentSource.GetSource(user == null ? null : user.getId());
jsonObject.put("group",group);
if (user == null) {
if (uploadConfig.getIsupdate() != 1) {
msg.setCode("1000");
@@ -314,13 +369,15 @@ public class UploadServicel {
return msg;
}
updatePath = "tourist";
group = GetCurrentSource.GetSource(null);
memory = Long.valueOf(uploadConfig.getVisitormemory()); // 单位 B 游客设置总量
TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists()); // 单位 B 游客单文件大小
UsedTotleMemory =
Long memory = Long.valueOf(uploadConfig.getVisitormemory()); // 单位 B 游客设置总量
Long TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists()); // 单位 B 游客单文件大小
Long UsedTotleMemory =
imgServiceImpl.getusermemory(0) == null
? 0L
: imgServiceImpl.getusermemory(0); // 单位 B
jsonObject.put("memory",memory);
jsonObject.put("TotleMemory",TotleMemory);
jsonObject.put("UsedTotleMemory",UsedTotleMemory);
} else {
if (uploadConfig.getUserclose() != 1) {
msg.setCode("1001");
@@ -328,20 +385,26 @@ public class UploadServicel {
return msg;
}
updatePath = user.getUsername();
group = GetCurrentSource.GetSource(user.getId());
memory = Long.valueOf(user.getMemory()); // 单位 B *1024*1024
TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser()); // 单位 B
UsedTotleMemory =
Long memory = Long.valueOf(user.getMemory()); // 单位 B *1024*1024
Long TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser()); // 单位 B
Long UsedTotleMemory =
imgServiceImpl.getusermemory(user.getId()) == null
? 0L
: imgServiceImpl.getusermemory(user.getId()); // 单位 B
jsonObject.put("memory",memory);
jsonObject.put("TotleMemory",TotleMemory);
jsonObject.put("UsedTotleMemory",UsedTotleMemory);
}
if (uploadConfig.getUrltype() == 2) {
updatePath = dateFormat.format(new Date());
LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
updatePath = currentDate.format(formatter);
}
jsonObject.put("updatePath",updatePath);
msg.setData(jsonObject);
msg.setCode("300");
} catch (Exception e) {
e.printStackTrace();
logger.error("updateImgCheck异常:",e);
msg.setCode("500");
}
return msg;
@@ -352,8 +415,6 @@ public class UploadServicel {
public static String plusDay(int setday) {
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currdate = format.format(d);
System.out.println("现在的日期是:" + currdate);
Calendar ca = Calendar.getInstance();
ca.setTime(d);
ca.add(Calendar.DATE, setday); // num为增加的天数,可以改变的
@@ -0,0 +1,210 @@
package cn.hellohao.service.impl;
import cn.hellohao.config.GlobalConstant;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.service.ImgService;
import cn.hellohao.service.KeysService;
import cn.hellohao.utils.TypeDict;
import com.github.sardine.impl.methods.HttpMkCol;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
@Service
public class WebDAVImageupload {
static CloseableHttpClient httpClient;
static Keys key;
@Autowired
private ImgService imgService;
@Autowired
private KeysService keysService;
private static Logger logger = LoggerFactory.getLogger(WebDAVImageupload.class);
public ReturnImage ImageuploadWebDAV(Map<Map<String, String>, File> fileMap, String username,Integer keyID) {
ReturnImage returnImage = new ReturnImage();
try {
if(null==httpClient || null==key){
System.out.println("WebDAV = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
} catch (Exception e) {
logger.error("ImageuploadWebDAV:61异常",e);
System.out.println("WebDAV = 存储源对象为空");
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();
createDirectories(httpClient, key.getEndpoint(), "/" + username);
HttpPut httpPut = new HttpPut(key.getEndpoint() + "/" + username + "/" + ShortUIDName + "." + prefix);
FileEntity fileEntity = new FileEntity(file, ContentType.DEFAULT_BINARY);
httpPut.setEntity(fileEntity);
HttpResponse response = httpClient.execute(httpPut);
final int statusCode = response.getStatusLine().getStatusCode();
logger.info("WebDav上传响应代码:"+statusCode);
EntityUtils.consume(response.getEntity());
if(statusCode >= 200 && statusCode < 300){
returnImage.setCode("200");
}else{
returnImage.setCode(Integer.toString(statusCode));
}
}
} catch (Exception e) {
logger.error("ImageuploadWebDAV:87异常",e);
returnImage.setCode("500");
}
return returnImage;
}
//webdav初始化
public static Integer Initialize(Keys k) {
int ret = -1;
try {
if(k.getSysTransmit()==false){
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getRequestAddress())) {
return -1;
}
}else{
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getEndpoint())) {
return -1;
}
}
String endpoint = k.getEndpoint();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(k.getAccessKey(), k.getAccessSecret()));
CloseableHttpClient httpClientObj = HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
HttpUriRequest request = RequestBuilder.create("PROPFIND")
.setUri(endpoint +"/"+ k.getRootPath())
.addHeader("Depth", "1")
.setEntity(new StringEntity(
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<D:propfind xmlns:D=\"DAV:\">\n" +
" <D:allprop/>\n" +
"</D:propfind>",
ContentType.create("text/xml", "UTF-8")))
.build();
HttpResponse response = httpClientObj.execute(request);
System.out.println("=====>"+response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode()==207 || response.getStatusLine().getStatusCode()==404){
ret = 1;
httpClient = httpClientObj;
key = k;
}else {
return -1;
}
EntityUtils.consume(response.getEntity());
} catch (Exception e) {
logger.error("WebDAV初始化失败", e);
return -1;
}
return ret;
}
public Boolean delWebDAV(Integer keyID, Images images) {
boolean b = true;
try {
Keys keys = keysService.selectKeys(images.getSource());
String rootPath = keys.getRootPath().equals("/")?"":keys.getRootPath();
String fileUrl = keys.getEndpoint()+"/"+images.getImgname();
System.err.println("删除缩yuan图:"+fileUrl);
HttpDelete httpDelete = new HttpDelete(fileUrl);
HttpResponse response = httpClient.execute(httpDelete);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 204) {
logger.info("File deleted: " + fileUrl);
// checkAndDeleteEmptyParentDirectories(httpClient,fileUrl);
} else {
logger.error("Failed to delete file: " + fileUrl);
}
EntityUtils.consume(response.getEntity());
} catch (Exception e) {
logger.error("WebDav删除异常:",e);
b = false;
}
return b;
}
public ResponseEntity<InputStreamResource> getWebDAV(String shortUuid) {
boolean b = true;
try {
Images images = null;
images = imgService.selectImgByShortlink(shortUuid);
Keys keys = keysService.selectKeys(images.getSource());
String rootPath = keys.getRootPath().equals("/")?"":keys.getRootPath();
String fileUrl = keys.getEndpoint()+"/"+images.getImgname();
HttpGet httpGet = new HttpGet(fileUrl);
HttpResponse response = httpClient.execute(httpGet);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "image/jpeg");
return ResponseEntity.ok()
.headers(headers)
.body(new InputStreamResource(response.getEntity().getContent()));
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
private static void createDirectories(CloseableHttpClient httpClient, String baseUrl, String directoryPath) throws Exception {
String[] directories = directoryPath.split("/");
String currentPath = baseUrl;
for (String directory : directories) {
currentPath += directory + "/";
HttpMkCol httpMkCol = new HttpMkCol(currentPath);
HttpResponse response = httpClient.execute(httpMkCol);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
System.out.println("Directory created: " + currentPath);
} else if (statusCode == 405) {
System.out.println("Directory already exists: " + currentPath);
} else {
System.err.println("Failed to create directory: " + currentPath);
}
EntityUtils.consume(response.getEntity());
}
}
}
@@ -26,13 +26,14 @@ public class deleImages {
@Autowired private USSImageupload ussImageupload;
@Autowired private S3Imageupload s3Imageupload;
@Autowired private FtpServiceImpl ftpService;
@Autowired private WebDAVImageupload webDAVImageupload;
@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, Long... imgIds) {
public Msg dele(boolean forceDel,String uuid, Long... imgIds) {
Msg msg = new Msg();
MyProgress myProgress = new MyProgress();
myProgress.InitializeDelImg();
@@ -44,6 +45,20 @@ public class deleImages {
boolean isDele = false;
try {
Images image = imgService.selectByPrimaryKey(imgIds[i]);
if (forceDel) {
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());
}
}
Keys key = keysService.selectKeys(image.getSource());
if (key.getStorageType() == 1) {
isDele = nosImageupload.delNOS(key.getId(), image);
@@ -61,23 +76,26 @@ public class deleImages {
isDele = ftpService.delFTP(key.getId(), image);
} else if (key.getStorageType() == 8) {
isDele = s3Imageupload.deleS3(key.getId(), image);
}else if (key.getStorageType() == 9) {
isDele = webDAVImageupload.delWebDAV(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 (!forceDel) {
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);
@@ -134,6 +152,8 @@ public class deleImages {
ftpService.delFTP(key.getId(), image);
} else if (key.getStorageType() == 8) {
s3Imageupload.deleS3(key.getId(), image);
}else if (key.getStorageType() == 9) {
webDAVImageupload.delWebDAV(key.getId(), image);
} else {
System.err.println("未获取到对象存储参数,删除失败。");
}
@@ -1,29 +1,51 @@
package cn.hellohao.utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.util.Base64;
/**
* Created by Hellohao on 2019-08-27.
*/
public class Base64Encryption {
public static void toBaseCode(String str) {
String data = encryptBASE64(str.getBytes());
}
public static String decryptBASE64(String key) {
byte[] b =null;
try {
b = (new BASE64Decoder()).decodeBuffer(key);
} catch (IOException e) {
e.printStackTrace();
}
return new String(b);
}
public static String encryptBASE64(byte[] key) {
String string = "SGVsbG9oYW8K";
return (new BASE64Encoder()).encodeBuffer(key).replaceAll("\r|\n", "");
}
}
//package cn.hellohao.utils;
//
//import java.io.IOException;
//import java.util.Base64;
//
///**
// * Created by Hellohao on 2019-08-27.
// */
//public class Base64Encryption {
//// public static void toBaseCode(String str) {
//// String data = encryptBASE64(str.getBytes());
//// }
//// public static String decryptBASE64(String key) {
//// byte[] b =null;
//// try {
//// b = (new BASE64Decoder()).decodeBuffer(key);
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
//// return new String(b);
//// }
//// public static String encryptBASE64(byte[] key) {
//// String string = "SGVsbG9oYW8K";
//// return (new BASE64Encoder()).encodeBuffer(key).replaceAll("\r|\n", "");
//// }
//
//
// public static void toBaseCode(String str) {
// String data = encryptBASE64(str.getBytes());
// }
//
// public static String decryptBASE64(String key) {
// byte[] b = null;
// try {
// b = Base64.getDecoder().decode(key);
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// return new String(b);
// }
//
// public static String encryptBASE64(byte[] key) {
// String string = "SGVsbG9oYW8K";
// return Base64.getEncoder().encodeToString(key);
// }
//
//
//
//
//
//}
@@ -1,9 +1,9 @@
package cn.hellohao.utils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.util.Base64;
/**
* base64转为multipartFile工具类
@@ -74,21 +74,30 @@ public class Base64ToMultipartFile implements MultipartFile {
* @return
*/
public static MultipartFile base64Convert(String base64) {
String[] baseStrs = base64.split(",");
// String[] baseStrs = base64.split(",");
// BASE64Decoder decoder = new BASE64Decoder();
// byte[] b = new byte[0];
// try {
// b = decoder.decodeBuffer(baseStrs[1]);
// } catch (IOException e) {
// e.printStackTrace();
// }
// for (int i = 0; i < b.length; ++i) {
// if (b[i] < 0) {
// b[i] += 256;
// }
// }
// return new Base64ToMultipartFile (b, baseStrs[0]);
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
try {
b = decoder.decodeBuffer(baseStrs[1]);
} catch (IOException e) {
e.printStackTrace();
}
String[] baseStrs = base64.split(",");
byte[] b = Base64.getDecoder().decode(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new Base64ToMultipartFile (b, baseStrs[0]);
return new Base64ToMultipartFile(b, baseStrs[0]);
}
+31 -8
View File
@@ -111,6 +111,30 @@ public class FirstRun implements InitializingBean {
RunSqlScript.RunInsert(instartConfdata);
Print.Normal("Add table.confdata");
}
Integer ret7 =
RunSqlScript.RunSelectCount(judgeTable + " 'keys' and column_name = 'SysTransmit'");
if (ret7 == 0) {
RunSqlScript.RunInsert(sql7);
Print.Normal("Add keys.SysTransmit");
}
Integer ret8 =
RunSqlScript.RunSelectCount(judgeTable + " 'imgdata' and column_name = 'brieflink'");
if (ret8 == 0) {
RunSqlScript.RunInsert(sql8);
Print.Normal("Add imgdata.brieflink");
}
Integer ret9 =
RunSqlScript.RunSelectCount(judgeTable + " 'imgdata' and column_name = 'shortlink'");
if (ret9 == 0) {
RunSqlScript.RunInsert(sql9);
Print.Normal("Add imgdata.shortlink");
}
Integer ret10 =
RunSqlScript.RunSelectCount(" select count(*) from tbed.keys where storageType='9'");
if (ret10 == 0) {
RunSqlScript.RunInsert(sql10);
Print.Normal("Add Webdav Config");
}
RunSqlScript.RunInsert(index_imgdata);
RunSqlScript.RunInsert("ALTER TABLE tbed.`user` MODIFY id int auto_increment;");
Print.Normal("Stage success");
@@ -121,7 +145,6 @@ public class FirstRun implements InitializingBean {
//检查表是否存在,后边加'imgdata' and column_name = 'explains' 检查字段是否存在
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'";
@@ -130,12 +153,12 @@ public class FirstRun implements InitializingBean {
private String sql3 ="CREATE TABLE `imgandalbum` (`imgname` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`albumkey` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic";
private String sql4 ="CREATE TABLE `album` (`albumkey` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`albumtitle` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`createdate` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic";
private String sql6 = "alter table imgdata add explains varchar(5000)";
//添加album表字段userid
private String sql7 = "alter table album add userid int(10)";
//添加imgdata表字段md5key
private String sql8 = "alter table imgdata add md5key varchar(5000)";
private String sql7 =
"alter table `keys` add SysTransmit varchar(50) DEFAULT NULL ;";
private String sql8 = "alter table `imgdata` add brieflink varchar(100) DEFAULT null ;";
private String sql9 = "alter table `imgdata` add shortlink varchar(100) DEFAULT null ;";
// 图片标识名字段
private String sql11 = "alter table `imgdata` add idname varchar(255) DEFAULT '未命名' ;";
private String sql10 = "INSERT INTO `tbed`.`keys`(`id`, `AccessKey`, `AccessSecret`, `Endpoint`, `Bucketname`, `RequestAddress`, `storageType`, `keyname`, `Region`, `RootPath`, `SysTransmit`) VALUES (null, '账号', '密码', '连接', '', '存储源请求域名', 9, 'WebDAV', NULL, '/', NULL);";
private String sql12 = "alter table tbed.user add `token` varchar(255)";
//创建客户端程序相关表
@@ -188,9 +211,9 @@ public class FirstRun implements InitializingBean {
try {
File f = new File(filePath);
if (f.exists()) {
System.out.print("文件存在");
logger.info("文件存在");
} else {
System.out.print("文件不存在");
logger.info("文件不存在,准备创建");
// f.createNewFile();// 不存在则创建
FileUtil.createTempFile(f);
}
@@ -39,8 +39,6 @@ public class GetCurrentSource {
userService = userServiceImpl;
}
public static Group GetSource(Integer userid) {
//UserType 0-未分配 1-游客 2-用户 3-管理员
User user =null;
@@ -0,0 +1,89 @@
package cn.hellohao.utils;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.lang3.StringUtils;
public class GetProtocol {
private final static String HTTP= "http://";
private final static String HTTPS = "https://";
private String newurl;
//判断协议 能连接上则协议正确
public String getProtocol(String url,String referer) {
newurl = clearUrl(url);
url = HTTP + newurl;
if (exists(url,referer)) {
return url;
} else {
url = HTTPS + newurl;
if (exists(url,referer)) {
return url;
} else {
return null;
}
}
}
//清除URL里多余的符号
private String clearUrl(String url) {
if (url.contains(HTTP)) {
url = url.substring(url.lastIndexOf(HTTP) + HTTP.length());
for (int i = 0; i < url.length(); i++) {
if (url.charAt(i) == '/' || url.charAt(i) == '.'
|| url.charAt(i) == '\\') {
} else {
url = url.substring(i);
return url;
}
}
} else if (url.contains(HTTPS)) {
url = url.substring(url.lastIndexOf(HTTPS) + HTTPS.length());
for (int i = 0; i < url.length(); i++) {
if (url.charAt(i) == '/' || url.charAt(i) == '.'
|| url.charAt(i) == '\\') {
} else {
url = url.substring(i);
return url;
}
}
}else{
for (int i = 0; i < url.length(); i++) {
if (url.charAt(i) == '/' || url.charAt(i) == '.'
|| url.charAt(i) == '\\') {
} else {
url = url.substring(i);
return url;
}
}
}
return url;
}
//是否能连接上
private boolean exists(String url,String referer) {
try {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setConnectTimeout(3000);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
con.setRequestProperty("referer", StringUtils.isBlank(referer)?"no-referrer":referer);
System.out.println(con.getResponseCode() );
return (con.getResponseCode() == 200);
} catch (Exception e) {
return false;
}
}
public static void main(String[] args){
try {
String url = "https://img-blog.csdnimg.cn/cbf3201a3cfe4fc38a7cef006487158c.png";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String referer = con.getRequestProperty("Referer");
System.out.println("Referer: " + referer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -31,7 +31,8 @@ public class GetSource {
FtpServiceImpl ftpService;
@Autowired
S3Imageupload s3Imageupload;
@Autowired
WebDAVImageupload webDAVImageupload;
public ReturnImage storageSource(Integer type, Map<Map<String, String>, File> fileMap, String userpath,Integer keyID){
ReturnImage returnImage = null;
try {
@@ -51,6 +52,8 @@ public class GetSource {
returnImage = ftpService.FtpUploadFile(fileMap, userpath,keyID);
}else if(type==8){
returnImage = s3Imageupload.ImageuploadS3(fileMap, userpath,keyID);
}else if(type==9){
returnImage = webDAVImageupload.ImageuploadWebDAV(fileMap, userpath,keyID);
}
else{
new StorageSourceInitException("GetSource类捕捉异常:未找到存储源");
+18 -20
View File
@@ -2,6 +2,7 @@ package cn.hellohao.utils;
import cn.hellohao.TbedApplication;
import cn.hellohao.pojo.Msg;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;
@@ -64,7 +65,7 @@ public class ImgUrlUtil {
httpUrlConnection.setConnectTimeout(300000);
httpUrlConnection.setReadTimeout(300000);
httpUrlConnection.connect();
String code = new Integer(httpUrlConnection.getResponseCode()).toString();
String code = Integer.toString(httpUrlConnection.getResponseCode());
String message = httpUrlConnection.getResponseMessage();
System.out.println("getResponseCode code ="+ code);
System.out.println("getResponseMessage message ="+ message);
@@ -74,7 +75,7 @@ public class ImgUrlUtil {
throw new Exception("ResponseCode is not begin with 2,code="+code);
}
map.put("Check","true");
System.out.println("连接正常");
// System.out.println("连接正常");
}catch(Exception ex){
System.out.println(ex.getMessage());
}
@@ -83,15 +84,8 @@ public class ImgUrlUtil {
}
/**
* 从网络Url中下载文件
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static Map<String ,Object> downLoadFromUrl(String urlStr,String fileName,String savePath){
public static Map<String ,Object> downLoadFromUrl(String urlStr,String referer,String fileName,String savePath){
FileInputStream fileInputStream = null;
Map<String ,Object> resmap = new HashMap<>();
Map<String ,String> map = checkURLStatusCode(urlStr);
if(map.size()==0 || map.get("Check").equals("false")){
@@ -102,11 +96,11 @@ public class ImgUrlUtil {
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("referer", StringUtils.isBlank(referer) ? "no-referrer" : referer);
//设置超时间为3秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误 Referer
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
@@ -125,9 +119,9 @@ public class ImgUrlUtil {
inputStream.close();
}
//下载并且保存成功后 判断格式 如果不是图像格式 就删除
//
if(new File(saveDir+File.separator+fileName).exists()){
Msg msg = TypeDict.FileMiME(file);
fileInputStream = new FileInputStream(file);
Msg msg = TypeDict.FileMiME(fileInputStream);
if(msg.getCode().equals("200")){
File f = new File(saveDir+File.separator+fileName);
String imgPath = saveDir+File.separator+fileName+"."+(msg.getData().toString().replace("image/",""));
@@ -144,18 +138,22 @@ public class ImgUrlUtil {
resmap.put("res",false);
resmap.put("StatusCode","500");
}
if(fileInputStream!=null){
fileInputStream.close();
}
return resmap;
}catch (Exception e){
e.printStackTrace();
try{
if(fileInputStream!=null){
fileInputStream.close();
}
}catch (Exception e2){ }
resmap.put("res",false);
resmap.put("StatusCode","500");
return resmap;
}
}
/**
* 从输入流中获取字节数组
* @param inputStream
@@ -1,10 +1,14 @@
package cn.hellohao.utils;
import cn.hellohao.service.impl.S3Imageupload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
final class RunSqlScript {
private static Logger logger = LoggerFactory.getLogger(RunSqlScript.class);
public static String DBDRIVER = "com.mysql.cj.jdbc.Driver";
public static String DBURL ;
//现在使用的是mysql数据库,是直接连接的,所以此处必须有用户名和密码
@@ -21,7 +25,7 @@ final class RunSqlScript {
try {
Class.forName(DBDRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
logger.error("RunSqlScript[29]", e);
}
//2、连接数据库
//通过连接管理器连接数据库
@@ -29,14 +33,14 @@ final class RunSqlScript {
//在连接的时候直接输入用户名和密码才可以连接
conn = DriverManager.getConnection(DBURL,USERNAME,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
logger.error("RunSqlScript[36]", e);
}
//3、向数据库中插入一条数据
//String sql = "select count(*) from information_schema.columns where table_name = 'config' and column_name = 'id'";
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
logger.error("RunSqlScript[43]", e);
}
//4、执行语句
try {
@@ -46,7 +50,7 @@ final class RunSqlScript {
count = resultSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
logger.error("RunSqlScript[53]", e);
return -1;
}
//5、关闭操作
@@ -54,7 +58,7 @@ final class RunSqlScript {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
logger.error("RunSqlScript[61]", e);
}
return count;
}
@@ -71,8 +75,7 @@ final class RunSqlScript {
try {
Class.forName(DBDRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - ClassNotFoundException");
logger.error("RunSqlScript[78]", e);
}
//2、连接数据库
//通过连接管理器连接数据库
@@ -80,23 +83,21 @@ final class RunSqlScript {
//在连接的时候直接输入用户名和密码才可以连接
conn = DriverManager.getConnection(DBURL,USERNAME,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - SQLException1");
logger.error("RunSqlScript[86]", e);
}
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - SQLException2");
logger.error("RunSqlScript[91]", e);
}
//4、执行语句
try {
count = stmt.executeUpdate(sql);
} catch (SQLException e) {
if(e.getMessage().contains("Duplicate key name") && e.getMessage().contains("index_md5key_url")){
Print.Normal("Database index already exists, skip this step.");
logger.info("Database index already exists, skip this step.");
}else{
e.printStackTrace();
logger.error("RunSqlScript[100]", e);
}
}
//5、关闭操作
@@ -104,7 +105,7 @@ final class RunSqlScript {
stmt.close();
conn.close();
} catch (SQLException e) {
Print.Normal("SqlHelper.java - SQLException4");
logger.error("RunSqlScript[108]", e);
}
return count;
}
@@ -2,6 +2,9 @@ package cn.hellohao.utils;
import cn.hellohao.pojo.Chunk;
import cn.hellohao.pojo.Msg;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@@ -13,6 +16,7 @@ import java.text.DecimalFormat;
import java.util.stream.Stream;
public class SetFiles {
private static Logger logger = LoggerFactory.getLogger(SetFiles.class);
// 转换文件方法
public static File changeFile(MultipartFile multipartFile) {
// 获取文件名
@@ -47,17 +51,16 @@ public class SetFiles {
// 转换文件方法
public static File changeFile_new(MultipartFile multipartFile) {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();//getOriginalFilename
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = null;
try {
file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
String new_FileName = System.getProperty("java.io.tmpdir")+"hellohao_tmp_upload"+File.separator+fileName;
file = new File(new_FileName);
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
} catch (IOException e) {
e.printStackTrace();
logger.error("SetFiles.changeFile_new", e);
}
return file;
}
+1 -1
View File
@@ -57,6 +57,7 @@ public class SetText {
boolean flag = false;
try {
String check = "^\\w+@[a-zA-Z0-9]{2,10}(?:\\.[a-z]{2,4}){1,3}$";
// String regex = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; //这个也可以用
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
@@ -66,6 +67,5 @@ public class SetText {
return flag;
}
}
@@ -7,15 +7,16 @@ import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class TypeDict {
//apache大法
public static Msg FileMiME(File file ){
public static Msg FileMiME(InputStream stream){
final Msg msg = new Msg();
try {
Tika tika = new Tika();
String fileType = tika.detect(file);
String fileType = tika.detect(stream);
if (fileType != null && fileType.contains("/")) {
if(fileType.contains("image/")){
msg.setData(fileType);
@@ -30,22 +30,22 @@ private static final int VALICATE_CODE_LENGTH = 4;
* @param height
*/
private static void fillBackground(Graphics graphics, int width, int height) {
// 填充背景
graphics.setColor(Color.WHITE);
//设置矩形坐标x y 为0
graphics.fillRect(0, 0, width, height);
// 填充背景
graphics.setColor(Color.WHITE);
//设置矩形坐标x y 为0
graphics.fillRect(0, 0, width, height);
// 加入干扰线条
for (int i = 0; i < 8; i++) {
//设置随机颜色算法参数
graphics.setColor(RandomUtils.randomColor(40, 150));
Random random = new Random();
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x, y, x1, y1);
}
// 加入干扰线条
for (int i = 0; i < 8; i++) {
//设置随机颜色算法参数
graphics.setColor(RandomUtils.randomColor(40, 150));
Random random = new Random();
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x, y, x1, y1);
}
}
/**
@@ -59,15 +59,15 @@ graphics.drawLine(x, y, x1, y1);
*/
@Override
public String generate(int width, int height, OutputStream os) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
fillBackground(graphics, width, height);
String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
createCharacter(graphics, randomStr);
graphics.dispose();
//设置JPEG格式
ImageIO.write(image, "JPEG", os);
return randomStr;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
fillBackground(graphics, width, height);
String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
createCharacter(graphics, randomStr);
graphics.dispose();
//设置JPEG格式
ImageIO.write(image, "JPEG", os);
return randomStr;
}
/**
@@ -79,20 +79,20 @@ return randomStr;
*/
@Override
public VerifyCode generate(int width, int height) {
VerifyCode verifyCode = null;
try (
//将流的初始化放到这里就不需要手动关闭流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
String code = generate(width, height, baos);
verifyCode = new VerifyCode();
verifyCode.setCode(code);
verifyCode.setImgBytes(baos.toByteArray());
} catch (IOException e) {
logger.error(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
VerifyCode verifyCode = null;
try (
//将流的初始化放到这里就不需要手动关闭流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
String code = generate(width, height, baos);
verifyCode = new VerifyCode();
verifyCode.setCode(code);
verifyCode.setImgBytes(baos.toByteArray());
} catch (IOException e) {
logger.error(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
}
/**
@@ -102,15 +102,15 @@ return verifyCode;
* @param randomStr
*/
private void createCharacter(Graphics g, String randomStr) {
char[] charArray = randomStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
//设置RGB颜色算法参数
g.setColor(new Color(50 + RandomUtils.nextInt(100),
50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
//设置字体大小,类型
g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
//设置x y 坐标
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
}
}
char[] charArray = randomStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
//设置RGB颜色算法参数
g.setColor(new Color(50 + RandomUtils.nextInt(100),
50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
//设置字体大小,类型
g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
//设置x y 坐标
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
}
}
}
+9 -3
View File
@@ -4,11 +4,11 @@ server.port=10088
#前端域名需要带协议头http(s)://
CROS_ALLOWED_ORIGINS=${HELLOHAO_WEB_HOST:http://127.0.0.1:8080}
#数据库账号
spring.datasource.username=root
spring.datasource.username=${MYSQL_USERNAME:root}
#数据库密码test
spring.datasource.password=${MYSQL_PASS:root}
#数据库链接地址
spring.datasource.url=${MYSQL_URL:jdbc:mysql://127.0.0.1:3306/tbed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8}
spring.datasource.url=${MYSQL_URL:jdbc:mysql://localhost:3306/tbed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8}
#MySQL Driver 无需修改
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
@@ -49,4 +49,10 @@ 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
log4j2.formatMsgNoLookups=True
logging.level.cn.hellohao=DEBUG
logging.file.name=/HellohaoData/tbedlog/tbed.log
logging.pattern.console=%blue(%d{yyyy-MM-dd HH:mm:ss,SSS}) [%cyan(%t)] [%yellow(%c)]-[%highlight(%p)] %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
logging.logback.rollingpolicy.clean-history-on-start=true
logging.logback.rollingpolicy.max-history=7
+7 -5
View File
@@ -9,11 +9,12 @@
FROM
`album`
<where>
1=1
<if test="albumkey != null">
`albumkey` = #{albumkey}
and `albumkey` = #{albumkey}
</if>
<if test="userid != null">
`userid` = #{userid}
and `userid` = #{userid}
</if>
</where>
</select>
@@ -38,14 +39,15 @@
u.username
FROM `album` a LEFT JOIN user u on a.userid = u.id
<where>
1=1
<if test="albumkey != null">
`albumkey` like '%${albumkey}%'
and `albumkey` like CONCAT('%', #{albumkey}, '%')
</if>
<if test="username != null">
`username` like '%${username}%'
and `username` like CONCAT('%', #{username}, '%')
</if>
<if test="userid != null">
a.userid = #{userid}
and a.userid = #{userid}
</if>
</where>
order by a.createdate
@@ -9,6 +9,7 @@
FROM
`imgandalbum`
<where>
1=1
<if test="albumkey != null">
`albumkey` = #{albumkey}
</if>
@@ -21,6 +22,7 @@
FROM
`imgandalbum`
<where>
1=1
<if test="imgname != null">
`imgname` = #{imgname}
</if>
+47 -8
View File
@@ -53,11 +53,11 @@
<choose>
<when test="selecttype==1">
and
a.userid in ( SELECT id from `user` where username LIKE '%${username}%')
a.userid in ( SELECT id from `user` where username LIKE CONCAT('%', #{username}, '%'))
</when>
<otherwise>
and
a.userid not in ( SELECT id from `user` where username LIKE '%${username}%')
a.userid not in ( SELECT id from `user` where username LIKE CONCAT('%', #{username}, '%'))
</otherwise>
</choose>
</if>
@@ -71,12 +71,42 @@
and CONCAT(
imgurl,
idname
) LIKE '%${searchname}%'
) LIKE CONCAT('%', #{searchname}, '%')
</if>
<if test="idname != null and idname !=''">
and idname LIKE '%${idname}%'
and idname LIKE CONCAT('%', #{idname}, '%')
</if>
order by a.id desc
order by
<choose>
<when test="order == 'desc'">
a.updatetime desc
</when>
<when test="order == 'asc'">
a.updatetime asc
</when>
<when test="order == 'sizeAsc'">
CONVERT(a.sizes,SIGNED) asc
</when>
<when test="order == 'sizeDesc'">
CONVERT(a.sizes,SIGNED) desc
</when>
<otherwise>
a.updatetime desc
</otherwise>
</choose>
<!-- <if test="order == 'desc'">-->
<!-- a.updatetime desc-->
<!-- </if>-->
<!-- <if test="order == 'asc'">-->
<!-- a.updatetime asc-->
<!-- </if>-->
<!-- <if test="order == 'sizeAsc'">-->
<!-- CONVERT(a.sizes,SIGNED) asc-->
<!-- </if>-->
<!-- <if test="order == 'sizeDesc'">-->
<!-- CONVERT(a.sizes,SIGNED) desc-->
<!-- </if>-->
</select>
<insert id="insertImgData" parameterType="cn.hellohao.pojo.Images">
@@ -96,13 +126,14 @@
`format`,
about,
violation,
idname
idname,
brieflink,
shortlink
)
VALUES (null, #{imgname}, #{imgurl}, #{userid}, #{updatetime},#{sizes},#{abnormal},#{source},#{imgtype},
#{explains},#{md5key},#{imguid},#{format},#{about},null,#{idname})
#{explains},#{md5key},#{imguid},#{format},#{about},null,#{idname},#{brieflink},#{shortlink})
</insert>
<!-- 此用户下总数 -->
<select id="countimg" parameterType="integer" resultType="integer">
select count(*) from imgdata where userid = #{userid}
@@ -120,6 +151,14 @@
select * from imgdata where id = #{id}
</select>
<select id="selectImgByBrieflink" parameterType="string" resultType="cn.hellohao.pojo.Images">
select * from imgdata where binary brieflink = #{brieflink}
</select>
<select id="selectImgByShortlink" parameterType="string" resultType="cn.hellohao.pojo.Images">
select * from imgdata where binary shortlink = #{shortlink}
</select>
<select id="counts" resultType="integer">
select count(*) from imgdata where 1=1
<if test="userid != null">
+3 -1
View File
@@ -28,6 +28,7 @@
WHEN storageType=6 THEN '腾讯云'
WHEN storageType=7 THEN 'FTP'
WHEN storageType=8 THEN 'S3协议'
WHEN storageType=9 THEN 'WebDAV'
ELSE '未知' END AS storageName,
keyname
FROM `keys` GROUP BY storageType,id,storageName,keyname
@@ -51,7 +52,8 @@
RequestAddress = #{RequestAddress},
keyname = #{keyname},
Region = #{Region},
RootPath = #{RootPath}
RootPath = #{RootPath},
SysTransmit=#{SysTransmit}
WHERE
storageType = #{storageType}
</update>
+6 -13
View File
@@ -53,7 +53,6 @@
</where>
</select>
<!-- 查询当前用户:根据邮箱,根据id -->
<select id="getUsers" parameterType="cn.hellohao.pojo.User" resultType="cn.hellohao.pojo.User">
SELECT id,
username,
@@ -74,6 +73,9 @@
<if test="email != null">
and email = #{email}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="uid != null">
and uid = #{uid}
</if>
@@ -82,7 +84,7 @@
</if>
</where>
</select>
<!-- 查询当前用户:根据id -->
<select id="getUsersid" parameterType="integer" resultType="cn.hellohao.pojo.User">
SELECT id,
username,
@@ -98,7 +100,7 @@
FROM user
WHERE id = #{id}
</select>
<!-- 查询当前用户:根据uid -->
<select id="getUsersMail" parameterType="string" resultType="cn.hellohao.pojo.User">
SELECT id,
username,
@@ -115,13 +117,6 @@
WHERE uid = #{uid}
</select>
<!-- 插入图片信息 -->
<!-- <insert id="insertimg" parameterType="cn.hellohao.pojo.Images">-->
<!-- INSERT INTO imgdata (id, imgname, imgurl, userid, updatetime,sizes,abnormal,source,imgtype,md5key,imguid,format,about,violation)-->
<!-- VALUES (NULL, #{imgname}, #{imgurl}, #{userid}, #{updatetime},#{sizes},#{abnormal},#{source},#{imgtype},#{md5key},#{imguid},#{format},#{about},null)-->
<!-- </insert>-->
<!-- 修改资料 -->
<update id="change" parameterType="cn.hellohao.pojo.User">
UPDATE `user`
<set>
@@ -182,12 +177,10 @@
SELECT count(username) FROM `user` where username=#{username}
</select>
<!-- 查询用户总数 -->
<select id="getUserTotal" resultType="integer">
SELECT count(*) FROM `user`
</select>
<!-- 获取用户的详细信息 -->
<select id="getuserlist" resultType="cn.hellohao.pojo.User" parameterType="string">
SELECT
id,
@@ -210,7 +203,7 @@
and CONCAT(
username,
email
) LIKE '%${username}%'
) LIKE CONCAT('%', #{username}, '%')
</if>
order by birthder desc
</select>