94 Commits
Author SHA1 Message Date
hello-hao 733ec3e6f9 :rocket:修改配置文件,支持Docker部署 2023-03-21 21:15:31 +08:00
hello-hao c3e91f3593 :rocket:优化代码 2023-03-20 18:06:00 +08:00
hello-hao 8ebdbf6cee update:调整数据类型,删除逻辑
feat:sout在log文件中显示
2023-03-17 17:41:10 +08:00
hello-hao 393ad3138e update:调整了百度鉴别接口升级了依赖,新增了key的相关字段信息 2023-03-16 17:38:01 +08:00
hello-hao 6f6166275a feat:新增对接S3协议
style:调整日志框架
docs:调整了文档
2023-03-15 17:35:04 +08:00
hello-hao cc05712906 :rocket:修改存储源 2023-03-15 10:20:55 +08:00
hello-hao e61b7ce10d 📝 修改文件 2023-03-05 23:08:17 +08:00
hello-hao 1408b9c029 📝 修改文件 2023-03-05 14:28:34 +08:00
hello-hao f56bc84d29 :art:修改系统配置表数据结构,添加数据库连接检测 2023-03-03 18:59:12 +08:00
hello-hao f8a712e601 📝 2023-02-28 17:44:28 +08:00
hello-hao 4ca9159956 📝 修改文件 2023-01-01 23:27:08 +08:00
hello-hao 2048660b64 :rocket:修复筛选出现重复,记录图片原始名称等多个问题 2023-01-01 23:20:37 +08:00
hello-hao 2ee49dcae2 :art:完善部分新功能 2022-11-21 19:03:58 +08:00
hello-hao b978f33aba 📝 2022-11-20 22:29:04 +08:00
hello-hao d8bb6c1738 :art:完善部分新功能 2022-11-19 16:49:23 +08:00
hellohao e1018bde75 📝 2022-10-26 21:55:21 +08:00
hellohao 8c8e44f82c :rocket:优化验证码失效等问题 2022-10-26 21:51:25 +08:00
hellohao f61e672e54 📝 2022-09-05 16:44:16 +08:00
hellohao 4a5147b862 📝 2022-09-03 02:06:21 +08:00
hellohao f9374cbc0e :rocket:优化代码 2022-09-01 18:51:47 +08:00
hellohao 10b919be95 📝 2022-09-01 18:48:42 +08:00
hellohao 8d96a3d636 处理已知问题 2022-09-01 00:58:05 +08:00
hellohao a086e708b4 Merge branch 'hellohao-dev' 2022-09-01 00:50:36 +08:00
hellohao 903cd6c74a Merge remote-tracking branch 'origin/hellohao-dev' into hellohao-dev
# Conflicts:
#	src/main/java/cn/hellohao/utils/FirstRun.java
2022-09-01 00:49:58 +08:00
hellohao 7c5524c1ee 代码更新 2022-09-01 00:49:16 +08:00
hellohao 444f16dc2c Merge branch 'master' of https://github.com/Hello-hao/Tbed 2022-09-01 00:45:11 +08:00
hellohao d96096965f Merge branch 'master' into hellohao-dev 2022-09-01 00:39:17 +08:00
hello-hao 3d4ff813fe :art:完善部分新功能 2022-07-20 18:16:03 +08:00
hello-hao 9ac31c22ca :art:自动修改数据库字段大小 2022-07-20 10:28:49 +08:00
hellohao 5041d65612 代码更新 2022-07-19 22:57:12 +08:00
hellohao 196bbf8026 代码更新 2022-07-19 22:55:52 +08:00
hellohao d1942a5295 代码更新 2022-07-19 22:53:15 +08:00
hello-hao 9293c0d295 :art:完善部分新功能 2022-07-18 17:12:18 +08:00
hello-hao 1de06c6352 📝 2022-07-13 10:38:24 +08:00
hello-hao b9d020f7a6 📝 2022-07-13 10:23:01 +08:00
hellohao dcf753b2b3 代码更新 2022-07-12 22:41:44 +08:00
hellohao cec4db6947 代码更新 2022-07-12 19:59:39 +08:00
hellohao dc3736b4ce 代码更新 2022-07-10 22:11:34 +08:00
hello-hao 071eeaa3e7 :art:修复安全漏洞 2022-06-24 17:38:15 +08:00
hello-hao a71ca1c1e9 :art:完善部分新功能 2022-06-24 17:30:55 +08:00
hello-hao 133540874c 🔖 2022-05-26 21:03:03 +08:00
hello-hao cc683b7921 :art:优化代码结构 2022-05-09 16:46:40 +08:00
hello-hao cea9823899 📝 2022-05-06 18:00:01 +08:00
hello-hao 486cb48c81 📝 2022-05-06 17:45:46 +08:00
hello-hao ce333b790b :art:优化图像删除功能 2022-05-06 17:42:00 +08:00
hello-hao c53634ee9b 🔖 2022-04-21 22:43:33 +08:00
hello-hao 2ababe7beb 🔖 2022-04-21 22:31:39 +08:00
hello-hao aa7da62b35 🔖 2022-04-21 22:28:11 +08:00
hello-hao 91936fcb22 :bug:修复多个问题 2022-04-21 22:19:16 +08:00
hello-hao 8542ca2afc :art:完善新功能 2022-04-15 19:14:15 +08:00
hello-hao 5feabe5bf3 :art:完善新功能 2022-04-08 19:07:50 +08:00
hello-hao 10cafd8add 📝 2022-04-08 16:56:05 +08:00
hello-hao e528b75c76 📝 2022-04-08 16:51:06 +08:00
hello-hao 9d8827032e 📝 2022-04-07 10:50:01 +08:00
hello-hao a190bc5077 📝 2022-04-07 10:38:26 +08:00
hello-hao 6083ae97a3 :bug:修复代码问题 2022-04-07 10:35:56 +08:00
hello-hao 95889c42ef :bug:修复部分场景下出现的错误 2022-03-28 15:43:03 +08:00
hello-hao 9a6ce4d5eb 📝 2022-03-28 15:42:15 +08:00
hello-hao fdfd8391e3 📝 2022-03-28 15:12:59 +08:00
hello-hao 276d329276 :art:优化核心代码 2022-03-28 15:12:38 +08:00
hello-hao 2997d9ee72 :bug:修复问题优化代码 2022-03-17 13:42:57 +08:00
hello-hao c754825b93 📝 2022-02-27 16:52:02 +08:00
hello-hao 723a9c15ab 📝 2022-02-27 16:49:08 +08:00
hello-hao 4c6a19a4ab 🔖 2022-02-21 19:01:38 +08:00
hello-hao d09b5c2656 :bug:修复个人相册显示所有图片的错误逻辑,修复图像筛选功能,新增部分功能 2022-02-21 18:45:41 +08:00
hello-hao 68f175679f 🔖 2022-02-21 18:37:53 +08:00
hello-hao 43cfc832a8 :bug:紧急修复多个对象存储上传失败问题 2022-02-16 16:53:31 +08:00
hello-hao 6df3267b18 📝 2022-02-16 16:50:53 +08:00
hello-hao b0562203c2 📝 2022-02-11 14:14:11 +08:00
hello-hao 995582f7c6 📝 2022-02-08 13:41:13 +08:00
hello-hao e347ec2367 📝 2022-02-08 13:39:32 +08:00
hello-hao ffcd4dbf40 :bug:修复添加分发群组数据保存不全 2022-01-27 11:28:22 +08:00
hello-hao 6ee1673d83 :sparkles:分发群组/图像鉴别 2022-01-27 11:27:23 +08:00
hello-hao 7b0db6fe16 📝 2022-01-27 11:24:20 +08:00
hello-hao 1baed6a29a 📝 2021-12-29 14:05:39 +08:00
hello-hao a4855adbe6 :art:优化响应头和返回值判断逻辑 2021-12-29 11:12:24 +08:00
hello-hao b0cd5ca51f 📝 2021-12-15 10:28:03 +08:00
hello-hao 00b2f58916 📝 2021-11-29 11:34:33 +08:00
hello-hao 78b3206f65 🚑 2021-11-29 11:27:26 +08:00
hello-hao feb13edc66 📝 2021-11-29 11:21:56 +08:00
hello-hao 4700d79f35 📝 2021-11-16 14:14:40 +08:00
hello-hao 5a9bb8a509 📝 2021-11-01 11:16:43 +08:00
hello-hao 13bc21df93 📝 2021-11-01 10:36:44 +08:00
923453645@qq.com d4a4076d05 🔖 2021-10-29 22:46:13 +08:00
hello-hao 8390f355a8 :art:完善程序功能 2021-10-29 18:25:53 +08:00
hello-hao 8c0bef5127 🎨 2021-10-29 16:13:08 +08:00
hello-hao 696f8eac9c 🎨 2021-10-29 16:06:06 +08:00
hello-hao d6dd42546b 🎨 2021-10-29 16:00:10 +08:00
hello-hao 208a1a3c00 :art:优化核心代码 2021-10-29 15:03:35 +08:00
hello-hao 679094533f 📝 2021-10-29 14:58:53 +08:00
hello-hao ed695d7cb7 :wrench:更新配置文件 2021-10-29 14:46:05 +08:00
hello-hao 1dc014a231 :rocket:数据库表结构 2021-10-29 14:44:38 +08:00
hello-hao fd675264a5 :art:优化整体架构 2021-10-29 14:23:40 +08:00
hello-hao 738bd5873d :arrow_up:升级依赖 2021-10-29 14:07:02 +08:00
417 changed files with 3987 additions and 69480 deletions
+1
View File
@@ -3,3 +3,4 @@
*.css linguist-language=java *.css linguist-language=java
*.html linguist-language=java *.html linguist-language=java
+1
View File
@@ -74,3 +74,4 @@ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.ht
For answers to common questions about this code of conduct, see For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq https://www.contributor-covenant.org/faq
+1 -1
View File
@@ -658,4 +658,4 @@ specific requirements.
You should also get your employer (if you work as a programmer) or school, You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary. if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>. <https://www.gnu.org/licenses/>.
+139 -57
View File
@@ -1,117 +1,199 @@
# Hellohao图床 - 强大的图像托管服务程序 # Hellohao图像托管程序 - 也许这会是最优秀的图床程序
![宣传图Banner](https://upload.cc/i1/2022/02/11/HSg5tX.png)
![banner.png](http://img.wwery.com/Hellohao/HqXVDR2b.png)
![Visual Studio Marketplace Rating (Stars)](https://img.shields.io/visual-studio-marketplace/stars/ritwickdey.LiveServer?style=flat-square) ![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/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) ![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)
**Hellohao图像托管程序**这是一个基于多家对象存储源 JAVA语言编写SpringBoot框架开发的开源图像托管程序。
### 引导
[官网](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)
### 前言
**Hellohao图像托管程序**(图床)这是一个由JAVA语言编写SpringBoot框架开发的开源图像托管程序。具备多对象存储源对接,采用`前后端分离`式设计的一款专门托管图像的程序,支持多种格式的图像 多功能的图床系统。该程序支持除了`web端`之外,同时支持`客户端(win/mac`,`移动端(小程序)`等常用全平台支持。
程序主要使用领域:`个人照片存储``团队共享图像``博客/商城等网站图片托管``图像批量云分享`等。具备优秀的多用户图像上传功能和完善的图像查询管理逻辑,同时支持对接多家对象存储。 程序主要使用领域:`个人照片存储``团队共享图像``博客/商城等网站图片托管``图像批量云分享`等。具备优秀的多用户图像上传功能和完善的图像查询管理逻辑,同时支持对接多家对象存储。
**存储源支持:** **存储源支持:**
开源版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,`U-File`,`FTP` 开源版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,~~`U-File`~~,`FTP`
Core版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,`U-File`,`FTP`,`Backblaze(B2)`,`百度云BOS`,`青云Qingstor`,`Ucloud US3`,`Minio`,`AWS S3` Core版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`,~~`U-File`~~,`FTP`,`Backblaze(B2)`,`百度云BOS`,`青云Qingstor`,`Ucloud US3`,`Minio`,`AWS S3`等通用S3协议
### 更新日志 `20230101`
- 优化个人相册,适配右键菜单功能。
- 修复筛选全部图片时候出现重复的问题。
- 修复上传图片后不记录图片原始名称
- 调整了上传图像的代码逻辑
- 优化 ftp 上传逻辑
- 优化多线程上传图像的查重逻辑
- 新增用户协议相关协议内容展示
- 提高系统安全性
- 优化多个页面异常问题
[^_^]:程序宣传视频:[自制宣传视频](https://www.bilibili.com/video/BV11r4y1y7mH/)
[^_^]:官网(含Core版)[https://tbed.hellohao.cn](https://tbed.hellohao.cn)
[^_^]:前端源码:[https://github.com/Hello-hao/tbed-web](https://github.com/Hello-hao/tbed-web)
[^_^]:文档地址:[https://doc.hellohao.cn](https://doc.hellohao.cn)
[^_^]:程序展示:[https://tc.hellohao.cn](https://tc.hellohao.cn)
[^_^]:作者博客:[https://www.hellohao.cn](https://www.hellohao.cn)
[^_^]:官网(含Core版)(备用)[http://tbed.wwery.com](http://tbed.wwery.com)
[^_^]:文档地址(备用)[http://doc.wwery.com](http://doc.wwery.com)
[^_^]:程序展示(备用)[http://tc.wwery.com](http://tc.wwery.com)
[^_^]:作者博客(备用)[http://www.wwery.com](http://www.wwery.com)
## 重构版已经开始进行 ### 主要功能
### 程序宣传视频:[点击查看](https://www.bilibili.com/video/BV11r4y1y7mH/) - [x] 全端支持,不限于(`web端`/`桌面端Windows/Mac`/`移动端小程序`)
> 目前Core版本(付费版已经重构完成,即将发布正式版) - [x] 前后端分离式架构设计,部署更方便
> 开源版正在开发中
作者正在夜以继日的努力开发中,敬请期待! - [x] 个人相册浏览,图像详细资料展示卡片
源代码不可用请谅解,如需搭建请前往下载编译包直接部署。
主站地址(包含Core版购买地址): [http://tbed.hellohao.cn/](http://tbed.hellohao.cn/) - [x] 支持 图片拖拽、截图直接(Ctrl+V)
程序Demo: [http://tc.hellohao.cn](http://tc.hellohao.cn) - [x] 支持URL地址批量上传
开源版/Core版 文档地址: [http://doc.hellohao.cn](http://doc.hellohao.cn) - [x] 一键复制嵌入式链接代码,也可以自定义嵌入式代码格式
开源版编译包下载(内部版请前往主站获取): [https://github.com/Hello-hao/Tbed/releases/](https://github.com/Hello-hao/Tbed/releases/) - [x] 对接邮箱服务,注册/找回密码等功能
--- - [x] 违规图像实时多线程鉴别
> 一下是旧版程序的介绍和截图,等新版开发出来后再贴图 - [x] 图片定期暂存
## 系统预览
- [x] 图片名称记录/修改
- [x] 支持常见多种图像格式如:`webp`,`ico`,`svg`等等
- [x] 支持画廊批量分享模式
- [x] 账户图像查重上传
- [x] 配置IP黑名单操作
- [x] 站点上传可控API接口
- [x] 设置用户可用容量
- [x] 账户扩容码批量生成
- [x] 细致的上传分发配置,分发群组功能
- [x] 游客、用户的上传管理
- [x] 图像直链二维码生成
![图床后台管理.png](http://cdn.wwery.com/Hellohao/c208e0825054822.png)
![图床后台管理2.png](http://cdn.wwery.com/Hellohao/6c7690825054822.png) ### 系统预览
![图床后台管理3.png](http://cdn.wwery.com/Hellohao/2a79b0825054822.png)
![图床后台管理4.png](http://cdn.wwery.com/Hellohao/5c1800825054824.png) ![首页](https://upload.cc/i1/2022/02/11/t2wCEF.png)
![控制台详情](https://upload.cc/i1/2022/02/11/Al8UrH.png)
![相册](https://upload.cc/i1/2022/02/11/2LhEHJ.png)
![多存储源](https://upload.cc/i1/2022/02/11/gOPxZW.png)
![站点设置](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)
## 运行环境 ### 运行环境
- JDK 1.8 - JDK 1.8
- MySQL5.5+ - MySQL5.5+
- Redis
### 所用技术
## 部署 #### 前端主要技术
### 修改配置文件 - vue
- iview
- vuex
- axios
#### 后端主要技术
- SpringBoot
- MyBatis
- MySQL
- Maven
- JWT认证
- Shiro
打开 `application.properties` 修改 `MySQL``服务器端口` 等连接信息.
### 部署 ### 部署
前提是你的服务器必须要有`JDK1.8`环境,和`mysql`数据库。 > 部署方式分为两种:
> 1.一键脚本部署:`Tbed-together.zip`(操作简单)
```shell > 2.自定义部署 前后端分离式部署:`Tbed.zip`(拓展性高适合有一定java前后端分离部署经验的人)
#JDK安装命令 > 需要注意:一键部署的端口为:服务器:`10088` 前端:`10089`
yum install java-1.8*
```
`Tbed.jar``application.properties`放到服务器你想存放的目录比如`/home`,注意这两个文件必须要在同一目录下不能分开。
依次运行如下命令:
```shell
cd /home
java -jar Tbed.jar
```
详细部署教程参考程序[相关文档](http://doc.hellohao.cn)
### 启动项目 ### 启动项目
启动后访问地址为:http://localhost:8088 , `8088`就是你配置`server.port=8088`的端口. 初始用户名:`admin`
初始邮箱:`admin`
初始密码:`admin`
初始用户名:admin ### 客户端(win64/mac)
初始邮箱:admin > 目前已经正式上线
初始密码`admin` ![桌面客户端软件](https://upload.cc/i1/2022/07/13/5W8Pxh.png)
注意:上边的`/home`是你的jar包和application.properties文件放的目录。 ### 微信小程序
项目运行起来不要关闭xshell窗口,否则项目将不能访问。可以使用一些后台命令把项目锁定后台。如`nohup``screen`,推荐使用`screen` > 目前已有测试版,更多功能开发中,开发进度的快慢要根据作者的工作压力、心情状况等自身情况进行评估。
> 暂时无法给出具体发布小程序的时间。大家期待吧。
### PC客户端 ![Hellohao图像托管](https://upload.cc/i1/2022/03/28/Vnp0bT.png)
作者精力不够,工作繁忙,暂停更新 [^_^]: ![小程序UI](https://upload.cc/i1/2022/02/11/6kPmr8.png)
### 声明 ### 声明
程序免费提供给个人用户使用,未经允许不得作为盈利商业使用,如果你想商用或程序定制,请先与我们联系,分享你的利益 项目遵循[GNU Affero General Public License v3.0](https://choosealicense.com/licenses/agpl-3.0/#)开源协议,使用前请悉知
源码仅供感兴趣的开发者做开发逻辑参考,不得在未经开发者同意的情况下以他人名义修改并发布使用编译包 如果你想商用或程序定制,请先与我们联系,分享你的利益
如果你想个人修改并使用我的源码,请保留原作者的版权,并开源你修改过的源码。
### 反馈交流 ### 反馈交流
**如果你遇到BUG可以去我的博客反馈** **如果你遇到BUG欢迎反馈**
Hellohao博客: [http://www.hellohao.cn/](http://www.hellohao.cn/) - 前往论坛发帖反馈、求助:[Hellohao开发者交流论坛](http://bbs.hellohao.cn)
- 也可加QQ群探讨(目前已满):864800972
欢迎加入Hellohao开发者交流群,群聊号码:**864800972**
### 捐赠开发者 ### 捐赠开发者
**如果你也支持Hellohao图床,可以请我喝杯咖啡。我会持续更新Hellohao图床** **如果你也支持Hellohao图床,可以请我喝杯咖啡。我会持续更新Hellohao图床**
**捐赠地址:** [**http://tbed.hellohao.cn/pay**](http://tbed.hellohao.cn/pay) **捐赠地址:** [**https://tbed.hellohao.cn/pay**](https://tbed.hellohao.cn/pay)
+17
View File
@@ -0,0 +1,17 @@
FROM openjdk:8
MAINTAINER 923453645@qq.com
ADD hellohaotbed/ /hellohaotbed
COPY appstart.sh /appstart.sh
COPY application.properties /application.properties
COPY Tbed.jar /Tbed.jar
EXPOSE 10088
EXPOSE 10089
CMD ["/bin/bash","/appstart.sh"]
+14 -39
View File
@@ -6,7 +6,7 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version> <version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/>
</parent> </parent>
<groupId>cn.hellohao</groupId> <groupId>cn.hellohao</groupId>
<artifactId>Tbed</artifactId> <artifactId>Tbed</artifactId>
@@ -58,9 +58,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- 自定义依赖添加 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
@@ -70,29 +67,19 @@
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId> <artifactId>shiro-spring</artifactId>
<version>1.7.1</version> <version>1.9.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.auth0</groupId> <groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId> <artifactId>java-jwt</artifactId>
<version>3.16.0</version> <version>3.16.0</version>
</dependency> </dependency>
<!-- 下边两个都是为了检查类型-->
<!-- https://mvnrepository.com/artifact/jmimemagic/jmimemagic -->
<!-- <dependency>-->
<!-- <groupId>jmimemagic</groupId>-->
<!-- <artifactId>jmimemagic</artifactId>-->
<!-- <version>0.1.2</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
<dependency> <dependency>
<groupId>org.apache.tika</groupId> <groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId> <artifactId>tika-core</artifactId>
<version>2.0.0</version> <version>2.0.0</version>
</dependency> </dependency>
<!-- 实体类标识注解如:不能为空 最大长度 等 -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId> <artifactId>spring-tx</artifactId>
@@ -103,11 +90,11 @@
<artifactId>spring-boot-starter-validation</artifactId> <artifactId>spring-boot-starter-validation</artifactId>
</dependency> </dependency>
<dependency> <!-- <dependency>-->
<groupId>commons-logging</groupId> <!-- <groupId>commons-logging</groupId>-->
<artifactId>commons-logging</artifactId> <!-- <artifactId>commons-logging</artifactId>-->
<version>1.2</version> <!-- <version>1.2</version>-->
</dependency> <!-- </dependency>-->
<dependency> <dependency>
<groupId>com.github.pagehelper</groupId> <groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId> <artifactId>pagehelper-spring-boot-starter</artifactId>
@@ -118,15 +105,10 @@
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.5.13</version> <version>4.5.13</version>
</dependency> </dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.httpcomponents</groupId>-->
<!-- <artifactId>httpmime</artifactId>-->
<!-- <version>4.5.12</version>-->
<!-- </dependency>-->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.76</version> <version>2.0.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
@@ -138,7 +120,11 @@
<artifactId>pebble</artifactId> <artifactId>pebble</artifactId>
<version>3.1.5</version> <version>3.1.5</version>
</dependency> </dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.334</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId> <artifactId>spring-boot-starter-mail</artifactId>
@@ -148,7 +134,7 @@
<dependency> <dependency>
<groupId>com.baidu.aip</groupId> <groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId> <artifactId>java-sdk</artifactId>
<version>4.11.0</version> <version>4.16.14</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.coobird</groupId> <groupId>net.coobird</groupId>
@@ -171,7 +157,6 @@
<version>0.0.4</version> <version>0.0.4</version>
</dependency> </dependency>
<!-- 对象存储依赖-->
<dependency> <dependency>
<groupId>com.netease.cloud</groupId> <groupId>com.netease.cloud</groupId>
<artifactId>nos-sdk-java-publiccloud</artifactId> <artifactId>nos-sdk-java-publiccloud</artifactId>
@@ -192,7 +177,6 @@
<artifactId>activation</artifactId> <artifactId>activation</artifactId>
<version>1.1.1</version> <version>1.1.1</version>
</dependency> </dependency>
<!-- no more than 2.3.3-->
<dependency> <dependency>
<groupId>org.glassfish.jaxb</groupId> <groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId> <artifactId>jaxb-runtime</artifactId>
@@ -231,15 +215,6 @@
<version>5.2.6.RELEASE</version> <version>5.2.6.RELEASE</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!-- 解析xml的依赖-->
<!-- <dependency>-->
<!-- <groupId>dom4j</groupId>-->
<!-- <artifactId>dom4j</artifactId>-->
<!-- <version>1.6.1</version>-->
<!-- </dependency>-->
</dependencies> </dependencies>
<build> <build>
+83 -64
View File
@@ -1,17 +1,17 @@
/* /*
Navicat Premium Data Transfer Navicat Premium Data Transfer
Source Server : localhost Source Server : locMysql
Source Server Type : MySQL Source Server Type : MySQL
Source Server Version : 50720 Source Server Version : 80028
Source Host : localhost:3306 Source Host : localhost:3306
Source Schema : tbed Source Schema : tbed
Target Server Type : MySQL Target Server Type : MySQL
Target Server Version : 50720 Target Server Version : 80028
File Encoding : 65001 File Encoding : 65001
Date: 28/10/2021 22:17:33 Date: 01/01/2023 23:02:40
*/ */
SET NAMES utf8mb4; SET NAMES utf8mb4;
@@ -26,23 +26,42 @@ CREATE TABLE `album` (
`albumtitle` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `albumtitle` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`createdate` varchar(255) 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(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`userid` int(10) NULL DEFAULT NULL `userid` int(0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ---------------------------- -- ----------------------------
-- Records of album -- Records of album
-- ---------------------------- -- ----------------------------
-- ----------------------------
-- Table structure for appclient
-- ----------------------------
DROP TABLE IF EXISTS `appclient`;
CREATE TABLE `appclient` (
`id` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`isuse` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`winpackurl` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`macpackurl` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`appname` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`applogo` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`appupdate` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of appclient
-- ----------------------------
INSERT INTO `appclient` VALUES ('app', 'on', '', '', 'Hellohao图像托管', 'https://hellohao.nos-eastchina1.126.net/TbedClient/app.png', '1.0.1');
-- ---------------------------- -- ----------------------------
-- Table structure for code -- Table structure for code
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `code`; DROP TABLE IF EXISTS `code`;
CREATE TABLE `code` ( CREATE TABLE `code` (
`id` int(255) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`value` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `value` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`code` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `code` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ---------------------------- -- ----------------------------
-- Records of code -- Records of code
@@ -53,24 +72,24 @@ CREATE TABLE `code` (
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `config`; DROP TABLE IF EXISTS `config`;
CREATE TABLE `config` ( CREATE TABLE `config` (
`id` int(4) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`sourcekey` int(4) NULL DEFAULT NULL, `sourcekey` int(0) NULL DEFAULT NULL,
`emails` int(4) NULL DEFAULT NULL COMMENT '邮箱配置', `emails` int(0) NULL DEFAULT NULL COMMENT '邮箱配置',
`webname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '网站名', `webname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '网站名',
`explain` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `explain` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`video` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `video` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`backtype` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '背景类型', `backtype` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '背景类型',
`links` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `links` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`notice` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `notice` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`baidu` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `baidu` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`domain` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `domain` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`background1` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `background1` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`background2` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `background2` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`sett` int(2) NOT NULL COMMENT '首页样式', `sett` int(0) NOT NULL COMMENT '首页样式',
`webms` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `webms` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webkeywords` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `webkeywords` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webfavicons` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `webfavicons` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`theme` int(4) NULL DEFAULT 1 COMMENT '主题', `theme` int(0) NULL DEFAULT 1 COMMENT '主题',
`websubtitle` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `websubtitle` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`logo` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `logo` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`aboutinfo` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `aboutinfo` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
@@ -80,38 +99,38 @@ CREATE TABLE `config` (
-- ---------------------------- -- ----------------------------
-- Records of config -- Records of config
-- ---------------------------- -- ----------------------------
INSERT INTO `config` VALUES (1, 7, 1, 'Hellohao图床', 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/books_x264.mp4http://cdn.wwery.com/Hellohao/439550606022825.jpg', '1', '<p style=\"color:#7c7c88;\">&copy; 2019 <a href=\"http://www.Hellohao.cn/\" target=\"_blank\" title=\"Hellohao\">Hellohao</a><span>&nbsp;&nbsp;- All Rights Reserved</span> </p>', '也许...|这将是最好用的图床|为了更好的用户体验,建议您注册本站继续免费使用Hellohao图床。本站不得上传任何形式的非法图片,一旦发现,永久删除并禁封账户。情节严重者将相关资料交于相关部门处理。', 'var _hmt = _hmt || [];\n(function() {\n var hm = document.createElement(\"script\");\n hm.src = \"https://hm.baidu.com/hm.js?16c326e608c984c9bae6a63eda861888\";\n var s = document.getElementsByTagName(\"script\")[0]; \n s.parentNode.insertBefore(hm, s);\n})();\n\n', 'http://api.hellohao.cn', '', 'http://cdn.wwery.com/Hellohao/3e1901120091153.jpg', 1, 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'hellohao图床,图床,图片上传,开源图床,hellohao,图像托管,图片分享', 'https://hellohao.nos-eastchina1.126.net/BlogImg/favicon.ico', 2, '这将是你用过最优秀的图像托管程序', NULL, '<img width=\"300px\" src=\"http://img.wwery.com/Hellohao/7SpMQnE3.png\">\n <br />\n <br />\n <p>也许,这将是你用到最优秀的图像托管程序</p>\n <p>本程序为Hellohao图象托管程序的重构Dev</p>\n <br/>\n <p style=\"color: #656565;\">作者:hellohao独立开发</p>\n <p style=\"color: #656565;\">www.hellohao.cn</p>'); INSERT INTO `config` VALUES (1, 7, 1, 'Hellohao图床', 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/books_x264.mp4http://cdn.wwery.com/Hellohao/439550606022825.jpg', '1', '<p style=\"color:#7c7c88;\">版权所有&copy;<a href=\"http://tbed.Hellohao.cn/\" target=\"_blank\" title=\"Hellohao\">Hellohao图像托管</a><span>&nbsp;2019- 2023 </span> </p>', '也许...|这将是最好用的图床|为了更好的用户体验,建议您注册本站继续免费使用Hellohao图床。本站不得上传任何形式的非法图片,一旦发现,永久删除并禁封账户。情节严重者将相关资料交于相关部门处理。', 'var _hmt = _hmt || [];\n(function() {\n var hm = document.createElement(\"script\");\n hm.src = \"https://hm.baidu.com/hm.js?16c326e608c984c9bae6a63eda861888\";\n var s = document.getElementsByTagName(\"script\")[0]; \n s.parentNode.insertBefore(hm, s);\n})();\n\n', 'http://api.hellohao.cn', '', 'http://cdn.wwery.com/Hellohao/3e1901120091153.jpg', 1, 'Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。', 'hellohao图床,图床,图片上传,开源图床,hellohao,图像托管,图片分享', 'https://hellohao.nos-eastchina1.126.net/BlogImg/favicon.ico', 2, '这将是你用过最优秀的图像托管程序', NULL, '<img width=\"300px\" src=\"http://img.wwery.com/Hellohao/rPscRYwz.png\">\n <br />\n <br />\n <p>也许,这将是你用到最优秀的图像托管程序</p>\n <p>本程序为Hellohao图象托管程序</p>\n <br/>\n <p style=\"color: #656565;\">作者:hellohao独立开发</p>\n <p style=\"color: #656565;\">www.hellohao.cn</p>');
-- ---------------------------- -- ----------------------------
-- Table structure for emailconfig -- Table structure for emailconfig
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `emailconfig`; DROP TABLE IF EXISTS `emailconfig`;
CREATE TABLE `emailconfig` ( CREATE TABLE `emailconfig` (
`id` int(2) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`emails` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱', `emails` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`emailkey` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '授权码', `emailkey` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '授权码',
`emailurl` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '服务器', `emailurl` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '服务器',
`port` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '端口', `port` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '端口',
`emailname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名', `emailname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名',
`using` int(4) NULL DEFAULT NULL COMMENT '1为可用,其他为不使用', `using` int(0) NULL DEFAULT NULL COMMENT '1为可用,其他为不使用',
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ---------------------------- -- ----------------------------
-- Records of emailconfig -- Records of emailconfig
-- ---------------------------- -- ----------------------------
INSERT INTO `emailconfig` VALUES (1, 'hellohao@hellohao.cn', '123456', 'smtp.qq.com', '465', 'Hellohao图床', 0); INSERT INTO `emailconfig` VALUES (1, '', '', '', '465', 'Hellohao图床', 0);
-- ---------------------------- -- ----------------------------
-- Table structure for group -- Table structure for group
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `group`; DROP TABLE IF EXISTS `group`;
CREATE TABLE `group` ( CREATE TABLE `group` (
`id` int(255) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`groupname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '组名称', `groupname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '组名称',
`keyid` int(255) NULL DEFAULT NULL, `keyid` int(0) NULL DEFAULT NULL,
`usertype` int(4) NULL DEFAULT NULL, `usertype` int(0) NULL DEFAULT NULL,
`compress` int(4) NULL DEFAULT NULL, `compress` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
@@ -140,24 +159,25 @@ INSERT INTO `imgandalbum` VALUES ('http://img.wwery.com/ccx51/5GBv93Ks.jpg', 'TO
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `imgdata`; DROP TABLE IF EXISTS `imgdata`;
CREATE TABLE `imgdata` ( CREATE TABLE `imgdata` (
`id` int(255) NOT NULL AUTO_INCREMENT COMMENT '主键', `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`imgname` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片名', `imgname` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片名',
`imgurl` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片链接', `imgurl` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片链接',
`userid` int(10) NULL DEFAULT NULL COMMENT '用户名', `userid` int(0) NULL DEFAULT NULL COMMENT '用户名',
`updatetime` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上传时间', `updatetime` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上传时间',
`sizes` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `sizes` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`abnormal` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `abnormal` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`source` int(2) NULL DEFAULT NULL COMMENT '存储源', `source` int(0) NULL DEFAULT NULL COMMENT '存储源',
`imgtype` int(2) NULL DEFAULT NULL, `imgtype` int(0) NULL DEFAULT NULL,
`explains` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `explains` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`md5key` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `md5key` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`imguid` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `imguid` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`format` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `format` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`about` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `about` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`violation` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `violation` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`idname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未命名图像',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `index_md5key_url`(`md5key`(255), `imgurl`(255)) USING BTREE INDEX `index_md5key_url`(`md5key`(255), `imgurl`(255)) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compressed; ) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compressed;
-- ---------------------------- -- ----------------------------
-- Records of imgdata -- Records of imgdata
@@ -168,12 +188,12 @@ CREATE TABLE `imgdata` (
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `imgreview`; DROP TABLE IF EXISTS `imgreview`;
CREATE TABLE `imgreview` ( CREATE TABLE `imgreview` (
`id` int(4) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`app_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `app_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`api_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `api_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`secret_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `secret_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`Using` int(4) NULL DEFAULT NULL, `Using` int(0) NULL DEFAULT NULL,
`count` int(255) NULL DEFAULT NULL COMMENT '拦截数量', `count` int(0) NULL DEFAULT NULL COMMENT '拦截数量',
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
@@ -187,7 +207,7 @@ INSERT INTO `imgreview` VALUES (1, '', '', '', 0, 0);
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `imgtemp`; DROP TABLE IF EXISTS `imgtemp`;
CREATE TABLE `imgtemp` ( CREATE TABLE `imgtemp` (
`id` int(255) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`imguid` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `imguid` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`deltime` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `deltime` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
@@ -202,13 +222,13 @@ CREATE TABLE `imgtemp` (
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `keys`; DROP TABLE IF EXISTS `keys`;
CREATE TABLE `keys` ( CREATE TABLE `keys` (
`id` int(11) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`AccessKey` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `AccessKey` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`AccessSecret` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `AccessSecret` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`Endpoint` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `Endpoint` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`Bucketname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `Bucketname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`RequestAddress` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `RequestAddress` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`storageType` int(11) NULL DEFAULT NULL, `storageType` int(0) NULL DEFAULT NULL,
`keyname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未定义策略名称' COMMENT '策略名称', `keyname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未定义策略名称' COMMENT '策略名称',
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
@@ -216,24 +236,22 @@ CREATE TABLE `keys` (
-- ---------------------------- -- ----------------------------
-- Records of keys -- Records of keys
-- ---------------------------- -- ----------------------------
INSERT INTO `keys` VALUES (1, '1', '1', '1', '1', '1', 2, '阿里云'); INSERT INTO `keys` VALUES (1, '', '', '', '', '', 2, '阿里云');
INSERT INTO `keys` VALUES (2, '1', '1', '1', '1', '1', 1, '网易云'); INSERT INTO `keys` VALUES (2, '', '', '', '', '', 1, '网易云');
INSERT INTO `keys` VALUES (3, '1', '1', '0', '1', '1', 3, '又拍'); INSERT INTO `keys` VALUES (3, '', '', '0', '', '', 3, '又拍');
INSERT INTO `keys` VALUES (4, '1', '1', '1', '1', '1', 4, '七牛云'); INSERT INTO `keys` VALUES (4, '', '', '', '', '', 4, '七牛云');
INSERT INTO `keys` VALUES (5, '0', '0', '0', '0', 'http://127.0.0.1:8088', 5, 'Localhost'); INSERT INTO `keys` VALUES (5, '0', '0', '0', '0', 'http://127.0.0.1:8089', 5, 'Localhost');
INSERT INTO `keys` VALUES (6, '1', '1', '1', '1', '1', 6, '腾讯云'); INSERT INTO `keys` VALUES (6, '', '', '', '', '', 6, '腾讯云');
INSERT INTO `keys` VALUES (8, '1', '1', '0', '1', '1', 8, 'UFile'); INSERT INTO `keys` VALUES (8, '', '', '0', '', '', 8, 'UFile');
INSERT INTO `keys` VALUES (9, '1', '1', '1', '1', '1', 9, 'B2'); INSERT INTO `keys` VALUES (13, '', '', '', '0', '', 7, 'ftp');
INSERT INTO `keys` VALUES (10, '1', '1', '1', '1', '1', 10, 'minio');
INSERT INTO `keys` VALUES (13, '1', '1', '1', '0', '1', 7, 'ftp');
-- ---------------------------- -- ----------------------------
-- Table structure for sysconfig -- Table structure for sysconfig
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `sysconfig`; DROP TABLE IF EXISTS `sysconfig`;
CREATE TABLE `sysconfig` ( CREATE TABLE `sysconfig` (
`id` int(2) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`register` int(2) NOT NULL COMMENT '是否可以注册', `register` int(0) NOT NULL COMMENT '是否可以注册',
`checkduplicate` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '0', `checkduplicate` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '0',
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
@@ -248,58 +266,59 @@ INSERT INTO `sysconfig` VALUES (1, 1, '0');
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `uploadconfig`; DROP TABLE IF EXISTS `uploadconfig`;
CREATE TABLE `uploadconfig` ( CREATE TABLE `uploadconfig` (
`id` int(2) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`filesizetourists` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `filesizetourists` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`filesizeuser` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `filesizeuser` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`imgcounttourists` int(10) NULL DEFAULT NULL COMMENT '游客文件总数量, 超出则不允许加入队列', `imgcounttourists` int(0) NULL DEFAULT NULL COMMENT '游客文件总数量, 超出则不允许加入队列',
`imgcountuser` int(10) NULL DEFAULT NULL COMMENT '用户文件总数量, 超出则不允许加入队列', `imgcountuser` int(0) NULL DEFAULT NULL COMMENT '用户文件总数量, 超出则不允许加入队列',
`suffix` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '支持后缀', `suffix` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '支持后缀',
`urltype` int(2) NULL DEFAULT NULL COMMENT 'url类型', `urltype` int(0) NULL DEFAULT NULL COMMENT 'url类型',
`isupdate` int(2) NULL DEFAULT NULL COMMENT '禁止游客上传', `isupdate` int(0) NULL DEFAULT NULL COMMENT '禁止游客上传',
`api` int(2) NOT NULL COMMENT '开启api', `api` int(0) NOT NULL COMMENT '开启api',
`visitormemory` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `visitormemory` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`usermemory` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `usermemory` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`blacklist` varchar(4000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `blacklist` varchar(4000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`userclose` int(4) NULL DEFAULT 0 COMMENT '用户上传开关', `userclose` int(0) NULL DEFAULT 0 COMMENT '用户上传开关',
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ---------------------------- -- ----------------------------
-- Records of uploadconfig -- Records of uploadconfig
-- ---------------------------- -- ----------------------------
INSERT INTO `uploadconfig` VALUES (1, '1048576', '5242880', 1, 5, 'gif,jpg,jpeg,bmp,png,jfif,webp,ico,svg', 1, 1, 1, '2147483648', '104857600', '', 1); INSERT INTO `uploadconfig` VALUES (1, '10485760', '20971520', 5, 10, 'gif,jpg,jpeg,bmp,png,jfif,webp', 1, 0, 0, '524288000', '104857600', '', 1);
-- ---------------------------- -- ----------------------------
-- Table structure for user -- Table structure for user
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `user`; DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` ( CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键', `id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`birthder` date NULL DEFAULT NULL COMMENT '注册时间', `birthder` date NULL DEFAULT NULL COMMENT '注册时间',
`level` int(10) NULL DEFAULT NULL COMMENT '等级', `level` int(0) NULL DEFAULT NULL COMMENT '等级',
`uid` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户唯一标识', `uid` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户唯一标识',
`isok` int(2) NOT NULL, `isok` int(0) NOT NULL,
`memory` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `memory` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`groupid` int(255) NULL DEFAULT NULL, `groupid` int(0) NULL DEFAULT NULL,
`token` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ---------------------------- -- ----------------------------
-- Records of user -- Records of user
-- ---------------------------- -- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', 'YWRtaW4=', 'admin', '2019-01-10', 2, 'a7d513e6e0084057a6f1c7b395ddbe6b', 1, '2147483648', 1); INSERT INTO `user` VALUES (1, 'admin', 'YWRtaW4=', 'admin', '2019-01-10', 2, '05bc9cdc2d454ab59e9cd7eaa9ed296a', 1, '2147483648', 1, '');
-- ---------------------------- -- ----------------------------
-- Table structure for usergroup -- Table structure for usergroup
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `usergroup`; DROP TABLE IF EXISTS `usergroup`;
CREATE TABLE `usergroup` ( CREATE TABLE `usergroup` (
`id` int(255) NOT NULL AUTO_INCREMENT, `id` int(0) NOT NULL AUTO_INCREMENT,
`userid` int(255) NULL DEFAULT NULL, `userid` int(0) NULL DEFAULT NULL,
`groupid` int(255) NULL DEFAULT NULL, `groupid` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
+34 -9
View File
@@ -1,24 +1,23 @@
package cn.hellohao; package cn.hellohao;
import javax.servlet.MultipartConfigElement; import cn.hellohao.dao.KeysMapper;
import javax.servlet.http.HttpServletRequest; import cn.hellohao.utils.FirstRun;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import cn.hellohao.utils.Print;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.support.DatabaseStartupValidator;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.unit.DataSize; import org.springframework.util.unit.DataSize;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.net.InetAddress; import javax.servlet.MultipartConfigElement;
import java.util.Scanner; import javax.sql.DataSource;
import java.util.stream.Stream;
@SpringBootApplication @SpringBootApplication
@Configuration @Configuration
@@ -30,6 +29,32 @@ public class TbedApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(TbedApplication.class, args); SpringApplication.run(TbedApplication.class, args);
} }
//延缓Spring Boot启动时间直到数据库启动的方法
@Bean
public DatabaseStartupValidator databaseStartupValidator(DataSource dataSource) {
DatabaseStartupValidator databaseStartupValidator = new DatabaseStartupValidator();
databaseStartupValidator.setDataSource(dataSource);
databaseStartupValidator.setValidationQuery(DatabaseDriver.POSTGRESQL.getValidationQuery());
return databaseStartupValidator;
}
@Bean
public static BeanFactoryPostProcessor dependsOnPostProcessor() {
return bf -> {
// Let beans that need the database depend on the DatabaseStartupValidator
// like the JPA EntityManagerFactory or Flyway
String[] flyway = bf.getBeanNamesForType(FirstRun.class);
Stream.of(flyway)
.map(bf::getBeanDefinition)
.forEach(it -> it.setDependsOn("databaseStartupValidator"));
String[] jpa = bf.getBeanNamesForType(KeysMapper.class);
Stream.of(jpa)
.map(bf::getBeanDefinition)
.forEach(it -> it.setDependsOn("databaseStartupValidator"));
};
}
/** /**
* 文件上传配置 * 文件上传配置
* @return * @return
@@ -29,7 +29,6 @@ public class OriginFilter {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration(); CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true); corsConfiguration.setAllowCredentials(true);
// corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(allowedOrigins.replace(" ", "")));
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL)); corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL));
corsConfiguration.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL)); corsConfiguration.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
corsConfiguration.setAllowedMethods(Collections.singletonList(CorsConfiguration.ALL)); corsConfiguration.setAllowedMethods(Collections.singletonList(CorsConfiguration.ALL));
@@ -42,28 +41,3 @@ public class OriginFilter {
} }
//@Configuration
//public class OriginFilter implements WebMvcConfigurer {
//
// @Value("${CROS_ALLOWED_ORIGINS}")
// private String allowedOrigins;
//
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// // 允许跨域访问的路径
// registry.addMapping("/**")
// // 允许跨域访问的源
// .allowedOrigins("http://服务器Ip:9528","http://服务器Ip:9001")
// // 允许请求方法
// .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
// // 预检间隔时间
// .maxAge(168000)
// // 允许头部设置
// .allowedHeaders("*")
// // 是否发送cookie
// .allowCredentials(true);
// }
//
//}
@@ -32,9 +32,10 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
HttpServletResponse httpServletResponse =(HttpServletResponse) response; HttpServletResponse httpServletResponse =(HttpServletResponse) response;
String serviceName = httpServletRequest.getServletPath();//获取接口 String serviceName = httpServletRequest.getServletPath();//获取接口
String Users_Origin = httpServletRequest.getHeader("usersOrigin"); String Users_Origin = httpServletRequest.getHeader("usersOrigin");
String token = httpServletRequest.getHeader("Authorization");
//验证前端域名 //验证前端域名
if(httpServletRequest.getMethod().equals("POST") && !serviceName.contains("/api") && !serviceName.contains("/verifyCode")){ if(httpServletRequest.getMethod().equals("POST") && !serviceName.contains("/api") && !serviceName.contains("/verifyCode")
&& !serviceName.contains("/getClientVersion") && !serviceName.contains("/client")){
try{ try{
if(Users_Origin.compareTo(SecureUtil.md5(WEBHOST))!=0){ if(Users_Origin.compareTo(SecureUtil.md5(WEBHOST))!=0){
System.out.println("前端域名校验未通过"); System.out.println("前端域名校验未通过");
@@ -50,10 +51,40 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
return false; return false;
} }
} }
String token = httpServletRequest.getHeader("Authorization");
if(serviceName.contains("/client")){
token = httpServletRequest.getHeader("jwttoken");
String userToken = httpServletRequest.getHeader("userToken");
User user = new User();
user.setToken(userToken);
User userData = userService.loginByToken(userToken);
if(null==userData){
this.CODE = "110404";
return false;
}else{
if(userData.getIsok()<1){
this.CODE = "110403";
return false;
}
Subject sub = SecurityUtils.getSubject();
User u = (User) sub.getPrincipal();
if(null==u){
httpServletRequest.getSession().setAttribute("user",userData);
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();
}
}
}
// String token = httpServletRequest.getHeader("Authorization");
JSONObject jsonObject = JWTUtil.checkToken(token); JSONObject jsonObject = JWTUtil.checkToken(token);
if(!jsonObject.getBoolean("check")){ if(!jsonObject.getBoolean("check")){
if(!serviceName.contains("admin")){ if(!serviceName.contains("admin") || serviceName.contains("admin/client")){
return true; return true;
}else{ }else{
this.CODE = "403"; this.CODE = "403";
@@ -102,6 +133,10 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter {
info = "当前用户无权访问该请求"; info = "当前用户无权访问该请求";
}else if(this.CODE.equals("402")){ }else if(this.CODE.equals("402")){
info = "当前web请求不合规"; info = "当前web请求不合规";
}else if(this.CODE.equals("110403")){
info = "该账户暂时无法使用";
}else if(this.CODE.equals("110404")){
info = "用户未找到";
} }
System.err.println("拦截器False-"+info); System.err.println("拦截器False-"+info);
response.setContentType("application/json;charset=UTF-8"); response.setContentType("application/json;charset=UTF-8");
@@ -24,7 +24,6 @@ public class XssFilter implements Filter {
//由于我的@WebFilter注解配置的是urlPatterns="/*"(过滤所有请求),所以这里对不需要过滤的静态资源url,作忽略处理(大家可以依照具体需求配置) //由于我的@WebFilter注解配置的是urlPatterns="/*"(过滤所有请求),所以这里对不需要过滤的静态资源url,作忽略处理(大家可以依照具体需求配置)
String[] exclusionsUrls = {".js",".gif",".jpg",".png",".bmp",".css",".ico"};//,"/","/index","/admin/root/" String[] exclusionsUrls = {".js",".gif",".jpg",".png",".bmp",".css",".ico"};//,"/","/index","/admin/root/"
for (String str : exclusionsUrls) { for (String str : exclusionsUrls) {
//System.out.println(path.contains(str));
if (path.contains(str)) { if (path.contains(str)) {
filterChain.doFilter(servletRequest,servletResponse); filterChain.doFilter(servletRequest,servletResponse);
return; return;
@@ -89,8 +89,6 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
String line = ""; String line = "";
StringBuilder body = new StringBuilder(); StringBuilder body = new StringBuilder();
int counter = 0; int counter = 0;
// 读取POST提交的数据内容
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8"))); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
try { try {
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
@@ -43,17 +43,14 @@ public class ShiroConfig {
} }
//安全对象
@Bean @Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//关联UserRealm
defaultWebSecurityManager.setRealm(userRealm); defaultWebSecurityManager.setRealm(userRealm);
defaultWebSecurityManager.setRememberMeManager(null); defaultWebSecurityManager.setRememberMeManager(null);
return defaultWebSecurityManager; return defaultWebSecurityManager;
} }
//创建 realm 对象
@Bean(name = "userRealm") @Bean(name = "userRealm")
public UserRealm userRealm(){ public UserRealm userRealm(){
return new UserRealm(); return new UserRealm();
@@ -25,7 +25,6 @@ public class UserRealm extends AuthorizingRealm {
@Autowired @Autowired
private UserService userService; private UserService userService;
//授权
@Override @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
@@ -22,9 +22,7 @@ public class JWTUtil {
private static String EXPIRE_TIME = ""; private static String EXPIRE_TIME = "";
private static String SECRET = "www.hellohao.cn"; private static String SECRET = "www.hellohao.cn";
//生成Token
public static String createToken(User user){ public static String createToken(User user){
// Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,604800 );//单位秒,604800 为7天 calendar.add(Calendar.SECOND,604800 );//单位秒,604800 为7天
Algorithm algorithm = Algorithm.HMAC256(SECRET); Algorithm algorithm = Algorithm.HMAC256(SECRET);
@@ -33,14 +31,11 @@ public class JWTUtil {
.withClaim("username", user.getUsername()) .withClaim("username", user.getUsername())
.withClaim("uid", user.getUid()) .withClaim("uid", user.getUid())
.withClaim("password", user.getPassword()) .withClaim("password", user.getPassword())
//到期时间
.withExpiresAt(calendar.getTime()) .withExpiresAt(calendar.getTime())
//创建一个新的JWT,并使用给定的算法进行标记
.sign(algorithm); .sign(algorithm);
return token; return token;
} }
//验证Token
public static JSONObject checkToken(String token){ public static JSONObject checkToken(String token){
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();//验证对象 JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();//验证对象
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
@@ -68,13 +63,5 @@ public class JWTUtil {
} }
public static void main(String[] args) {
User user = new User();
user.setEmail("Hellohao@qq.com");
user.setUsername("Hellohao");
String token = createToken(user);
System.out.println(token);
checkToken(token);
// checkToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjM3NDYwOTUsImVtYWlsIjoiSGVsbG9oYW9AcXEuY29tIiwidXNlcm5hbWUiOiJIZWxsb2hhbyJ9.sFnAq1VU0wuiowaTtgJNNkMzRHPmRg4leNguhh0OMCA");
}
} }
@@ -0,0 +1,13 @@
package cn.hellohao.config;
import java.io.File;
/**
* @author Hellohao
* @version 1.0
* @date 29/11/2021 上午 10:35
*/
public class GlobalConstant {
public static String SYSTYPE = "LINUX";
public static String LOCPATH = File.separator + "HellohaoData";
}
@@ -0,0 +1,44 @@
package cn.hellohao.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.PrintStream;
import java.util.function.Consumer;
@Configuration
public class LogSystemProxy {
private final static Logger log = LoggerFactory.getLogger("proxy.system.log");
@PostConstruct
public void initProxy(){
log.debug("LogSystemProxy init .....");
System.setOut(getLoggerProxy(StdType.OUT));
System.setErr(getLoggerProxy(StdType.ERR));
}
private enum StdType{
OUT(System.out, log::info),
ERR(System.err, log::error),
;
PrintStream stream;
Consumer<String> consumer;
StdType(PrintStream stream,Consumer<String> consumer){
this.stream = stream;
this.consumer = consumer;
}
}
private PrintStream getLoggerProxy(StdType stdType){
return new PrintStream(stdType.stream){
@Override
public void print(String s) {
stdType.stream.print(s);
stdType.consumer.accept(s);
}
};
}
}
@@ -0,0 +1,52 @@
package cn.hellohao.config;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
//线程池
@Configuration
@EnableAsync
public class PoolConfig {
ThreadPoolProperties properties = new ThreadPoolProperties();
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getCorePoolSize());
executor.setMaxPoolSize(properties.getMaxPoolSize());
executor.setQueueCapacity(properties.getQueueCapacity());
executor.setThreadNamePrefix(properties.getThreadNamePrefix());
executor.setKeepAliveSeconds(properties.getKeepAliveTime());
executor.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown());
executor.setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds());
// 设置任务拒绝策略
/**
* 4种
* ThreadPoolExecutor类有几个内部实现类来处理这类情况:
- AbortPolicy 丢弃任务,抛RejectedExecutionException
- CallerRunsPolicy 由该线程调用线程运行。直接调用Runnable的run方法运行。
- DiscardPolicy 抛弃策略,直接丢弃这个新提交的任务
- DiscardOldestPolicy 抛弃旧任务策略,从队列中踢出最先进入队列(最后一个执行)的任务
* 实现RejectedExecutionHandler接口,可自定义处理器
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
@Data
class ThreadPoolProperties {
private int corePoolSize = 5;
private int maxPoolSize = 50;
private int keepAliveTime = 15;
private int queueCapacity = 6;
private String threadNamePrefix = "Tbed-Thread";
private boolean allowCoreThreadTimeout = false;
private boolean waitForTasksToCompleteOnShutdown = false;
private int awaitTerminationSeconds;
}
}
@@ -12,7 +12,7 @@ public class WebImgConfigurer implements WebMvcConfigurer {
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
String filePath = File.separator + "HellohaoData" + File.separator; String filePath = GlobalConstant.LOCPATH + File.separator;
registry.addResourceHandler("/ota/**").addResourceLocations("file:"+filePath); registry.addResourceHandler("/ota/**").addResourceLocations("file:"+filePath);
} }
@@ -4,8 +4,14 @@ import cn.hellohao.config.SysName;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.pojo.vo.PageResultBean; import cn.hellohao.pojo.vo.PageResultBean;
import cn.hellohao.service.*; import cn.hellohao.service.*;
import cn.hellohao.service.impl.*; import cn.hellohao.service.impl.AlbumServiceImpl;
import cn.hellohao.utils.*; 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;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
@@ -14,13 +20,17 @@ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/** /**
* @author Hellohao * @author Hellohao
@@ -31,102 +41,78 @@ import java.util.*;
@RequestMapping("/admin") @RequestMapping("/admin")
public class AdminController { public class AdminController {
@Autowired @Autowired private ImgService imgService;
private ImgService imgService; @Autowired private KeysService keysService;
@Autowired @Autowired private UserServiceImpl userService;
private KeysService keysService; @Autowired private ImgreviewService imgreviewService;
@Autowired @Autowired private UploadConfigService uploadConfigService;
private UserServiceImpl userService; @Autowired private CodeService codeService;
@Autowired @Autowired private AlbumService albumService;
private UserServiceImpl userServiceImpl; @Autowired AlbumServiceImpl albumServiceI;
@Autowired @Autowired private deleImages deleimages;
private ImgreviewService imgreviewService; @Autowired private IRedisService iRedisService;
@Autowired
private ImgTempService imgTempService;
@Autowired
private UploadConfigService uploadConfigService;
@Autowired
private CodeService codeService;
@Autowired
private ImgAndAlbumService imgAndAlbumService;
@Autowired
private AlbumService albumService;
@Autowired
AlbumServiceImpl albumServiceI;
@Autowired @PostMapping(value = "/overviewData")
private NOSImageupload nosImageupload;
@Autowired
private OSSImageupload ossImageupload;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private KODOImageupload kodoImageupload;
@Autowired
private USSImageupload ussImageupload;
@Autowired
private UFileImageupload uFileImageupload;
@Autowired
private FTPImageupload ftpImageupload;
@PostMapping(value = "/overviewData") //new
@ResponseBody @ResponseBody
public Msg overviewData(@RequestParam(value = "data", defaultValue = "") String data) { public Msg overviewData(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
user = userService.getUsers(user); user = userService.getUsers(user);
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
Imgreview imgreview = imgreviewService.selectByPrimaryKey(1);//查询非法个数 Imgreview imgreview = imgreviewService.selectByPrimaryKey(1);
Imgreview isImgreviewOK = imgreviewService.selectByusing(1);//查询有没有启动鉴别功能 Imgreview isImgreviewOK = imgreviewService.selectByusing(1);
//普通用户
String ok = "false"; String ok = "false";
jsonObject.put("myImgTotal", imgService.countimg(user.getId())); //我的图片数 jsonObject.put("myToken", user.getToken());
jsonObject.put("myAlbumTitle", albumService.selectAlbumCount(user.getId()));//我的画廊数量 jsonObject.put("myImgTotal", imgService.countimg(user.getId()));
//计算自己的百分比 已用量/分配量 jsonObject.put("myAlbumTitle", albumService.selectAlbumCount(user.getId()));
long memory = Long.valueOf(user.getMemory());//分配量 long memory = Long.valueOf(user.getMemory());
Long usermemory = imgService.getusermemory(user.getId())==null?0L:imgService.getusermemory(user.getId()); Long usermemory =
if(memory==0){ imgService.getusermemory(user.getId()) == null
jsonObject.put("myMemory","无容量"); ? 0L
}else{ : imgService.getusermemory(user.getId());
Double aDouble = Double.valueOf(String.format("%.2f", (((double)usermemory/(double)memory)*100))); if (memory == 0) {
if(aDouble>=999){ jsonObject.put("myMemory", "无容量");
jsonObject.put("myMemory",999); } else {
}else{ Double aDouble =
jsonObject.put("myMemory",aDouble); Double.valueOf(String.format("%.2f", (((double) usermemory / (double) memory) * 100)));
if (aDouble >= 999) {
jsonObject.put("myMemory", 999);
} else {
jsonObject.put("myMemory", aDouble);
} }
} }
jsonObject.put("myMemorySum",SetFiles.readableFileSize(memory)); jsonObject.put("myMemorySum", SetFiles.readableFileSize(memory));
if(user.getLevel()>1){ if (user.getLevel() > 1) {
ok = "true"; ok = "true";
//管理员 jsonObject.put("imgTotal", imgService.counts(null));
jsonObject.put("imgTotal", imgService.counts(null) ); //admin 站点图片数 jsonObject.put("userTotal", userService.getUserTotal());
jsonObject.put("userTotal", userService.getUserTotal()); //admin 用户个数 jsonObject.put("ViolationImgTotal", imgreview.getCount());
jsonObject.put("ViolationImgTotal", imgreview.getCount()); //admin 非法图片 jsonObject.put("ViolationSwitch", isImgreviewOK == null ? 0 : isImgreviewOK.getId());
jsonObject.put("ViolationSwitch", isImgreviewOK==null?0:isImgreviewOK.getId()); //admin 非法图片开关 jsonObject.put("VisitorUpload", uploadConfig.getIsupdate());
jsonObject.put("VisitorUpload", uploadConfig.getIsupdate());//是否禁用了游客上传 jsonObject.put(
jsonObject.put("VisitorMemory", SetFiles.readableFileSize(Long.valueOf(uploadConfig.getVisitormemory())));//访客共大小 "VisitorMemory",
if(uploadConfig.getIsupdate()!=1){ SetFiles.readableFileSize(Long.valueOf(uploadConfig.getVisitormemory()))); // 访客共大小
jsonObject.put("VisitorUpload", 0);//是否禁用了游客上传 if (uploadConfig.getIsupdate() != 1) {
jsonObject.put("VisitorProportion",100.00);//游客用量%占比 jsonObject.put("VisitorUpload", 0);
jsonObject.put("VisitorMemory", "禁用");//访客共大小 jsonObject.put("VisitorProportion", 100.00);
}else{ jsonObject.put("VisitorMemory", "禁用");
Long temp = imgService.getusermemory(0)==null?0:imgService.getusermemory(0); } else {
jsonObject.put("UsedMemory", (temp == null ? 0 : SetFiles.readableFileSize(temp)));//访客已用大小 Long temp = imgService.getusermemory(0) == null ? 0 : imgService.getusermemory(0);
if(Long.valueOf(uploadConfig.getVisitormemory())==0){ jsonObject.put("UsedMemory", (temp == null ? 0 : SetFiles.readableFileSize(temp)));
jsonObject.put("VisitorProportion",100.00);//游客用量%占比 if (Long.valueOf(uploadConfig.getVisitormemory()) == 0) {
}else if(Long.valueOf(uploadConfig.getVisitormemory())==-1){ jsonObject.put("VisitorProportion", 100.00);
jsonObject.put("VisitorProportion",0);//游客用量%占比 } else if (Long.valueOf(uploadConfig.getVisitormemory()) == -1) {
jsonObject.put("VisitorMemory", "无限");//访客共大小 jsonObject.put("VisitorProportion", 0);
}else{ jsonObject.put("VisitorMemory", "无限");
} else {
double sum = Double.valueOf(uploadConfig.getVisitormemory()); double sum = Double.valueOf(uploadConfig.getVisitormemory());
Double aDouble = Double.valueOf(String.format("%.2f", ((double) temp / sum) * 100)); Double aDouble = Double.valueOf(String.format("%.2f", ((double) temp / sum) * 100));
if(aDouble>=999){ if (aDouble >= 999) {
jsonObject.put("VisitorProportion",999);//游客用量%占比 jsonObject.put("VisitorProportion", 999);
}else{ } else {
jsonObject.put("VisitorProportion",aDouble);//游客用量%占比 jsonObject.put("VisitorProportion", aDouble);
} }
} }
} }
@@ -136,62 +122,77 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping(value = "/SpaceExpansion")
@PostMapping(value = "/SpaceExpansion")//new
@ResponseBody @ResponseBody
public Msg SpaceExpansion(@RequestParam(value = "data", defaultValue = "") String data) { public Msg SpaceExpansion(@RequestParam(value = "data", defaultValue = "") String data) {
final Msg msg = new Msg(); Msg msg = new Msg();
final JSONObject jsonObject = JSONObject.parseObject(data); JSONObject jsonObject = JSONObject.parseObject(data);
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
user = userService.getUsers(user); user = userService.getUsers(user);
if(user.getIsok()==0){ if (user.getIsok() == 0) {
msg.setCode("100403"); msg.setCode("100403");
msg.setInfo("你暂时无法使用此功能"); msg.setInfo("你暂时无法使用此功能");
return msg; return msg;
} }
if(null==user){ if (null == user) {
msg.setCode("100405"); msg.setCode("100405");
msg.setInfo("用户信息不存在"); msg.setInfo("用户信息不存在");
return msg; return msg;
}else{ } else {
long sizes = 0; long sizes = 0;
Code code = codeService.selectCodekey(jsonObject.getString("code")); Code code = codeService.selectCodekey(jsonObject.getString("code"));
if(null==code){ if (null == code) {
msg.setCode("100404"); msg.setCode("100404");
msg.setInfo("扩容码不存在,请重新填写"); msg.setInfo("扩容码不存在,请重新填写");
return msg; return msg;
} }
Long userMemory = Long.valueOf(user.getMemory()); Long userMemory = Long.valueOf(user.getMemory());
sizes = Long.valueOf(code.getValue())+ userMemory; sizes = Long.valueOf(code.getValue()) + userMemory;
User newMemoryUser = new User(); User newMemoryUser = new User();
newMemoryUser.setMemory(Long.toString(sizes)); newMemoryUser.setMemory(Long.toString(sizes));
newMemoryUser.setId(user.getId()); newMemoryUser.setId(user.getId());
userService.usersetmemory(newMemoryUser,jsonObject.getString("code")); userService.usersetmemory(newMemoryUser, jsonObject.getString("code"));
msg.setInfo("你已成功扩容"+SetFiles.readableFileSize(sizes)); msg.setInfo("你已成功扩容" + SetFiles.readableFileSize(sizes));
return msg; return msg;
} }
} }
@PostMapping(value = {"/setImgFileName", "/client/setImgFileName"})
@PostMapping("/getRecently")//new 获取榜单和最近上传
@ResponseBody @ResponseBody
public Msg getRecently(@RequestParam(value = "data", defaultValue = "") String data) { public Msg setImgFileName(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
final JSONObject jsonObject = new JSONObject(); try {
JSONObject jsonObject = JSONObject.parseObject(data);
String name = jsonObject.getString("name");
String imgname = jsonObject.getString("imgname");
Images images = new Images();
images.setIdname(name.replaceAll(" ", ""));
images.setImgname(imgname);
imgService.setImg(images);
} catch (Exception e) {
e.printStackTrace();
msg.setCode("500");
}
return msg;
}
@PostMapping("/getRecently")
@ResponseBody
public Msg getRecently() {
Msg msg = new Msg();
JSONObject jsonObject = new JSONObject();
try { try {
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
user = userService.getUsers(user); user = userService.getUsers(user);
if(user.getLevel()>1){ if (user.getLevel() > 1) {
//管理员 可以看榜单数据 和最近上传 jsonObject.put("RecentlyUser", imgService.RecentlyUser());
jsonObject.put("RecentlyUser",imgService.RecentlyUser()); jsonObject.put("RecentlyUploaded", imgService.RecentlyUploaded(user.getId()));
jsonObject.put("RecentlyUploaded",imgService.RecentlyUploaded(user.getId())); } else {
}else{ jsonObject.put("RecentlyUploaded", imgService.RecentlyUploaded(user.getId()));
//普通用户只能看最近上传
jsonObject.put("RecentlyUploaded",imgService.RecentlyUploaded(user.getId()));
} }
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setInfo("系统内部错误"); msg.setInfo("系统内部错误");
msg.setCode("500"); msg.setCode("500");
@@ -201,55 +202,78 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping("/getYyyy")//new @PostMapping("/updateToken")
@ResponseBody @ResponseBody
public Msg getYyyy(@RequestParam(value = "data", defaultValue = "") String data){ public Msg updateToken() {
final Msg msg = new Msg(); Msg msg = new Msg();
try {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
User u = new User();
u.setId(user.getId());
u.setToken(UUID.randomUUID().toString().replace("-", ""));
userService.changeUser(u);
user.setToken(u.getToken());
msg.setData(u.getToken());
msg.setInfo("Token更新成功,即可生效");
} catch (Exception e) {
e.printStackTrace();
msg.setCode("500");
msg.setInfo("Token更新失败");
}
return msg;
}
@PostMapping("/getYyyy")
@ResponseBody
public Msg getYyyy() {
Msg msg = new Msg();
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
final JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("allYyyy",imgService.getyyyy(null)); jsonObject.put("allYyyy", imgService.getyyyy(null));
jsonObject.put("userYyyy",imgService.getyyyy(u.getId())); jsonObject.put("userYyyy", imgService.getyyyy(u.getId()));
msg.setData(jsonObject); msg.setData(jsonObject);
return msg; return msg;
} }
@PostMapping("/getChart")//new @PostMapping("/getChart")
@ResponseBody @ResponseBody
public Msg getChart(@RequestParam(value = "data", defaultValue = "") String data){ public Msg getChart(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
JSONObject jsonObject = JSONObject.parseObject(data); JSONObject jsonObject = JSONObject.parseObject(data);
String yyyy = jsonObject.getString("yyyy"); String yyyy = jsonObject.getString("yyyy");
Integer type = jsonObject.getInteger("type"); Integer type = jsonObject.getInteger("type");
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
List<Images> list =null; List<Images> list = null;
if(u.getLevel()>1){ if (u.getLevel() > 1) {
if(type==2){ if (type == 2) {
Images images = new Images(); Images images = new Images();
images.setYyyy(yyyy); images.setYyyy(yyyy);
list = imgService.countByM(images); list = imgService.countByM(images);
}else{ } else {
Images images = new Images(); Images images = new Images();
images.setYyyy(yyyy); images.setYyyy(yyyy);
images.setUserid(u.getId()); images.setUserid(u.getId());
list = imgService.countByM(images); list = imgService.countByM(images);
} }
}else{ } else {
Images images = new Images(); Images images = new Images();
images.setYyyy(yyyy); images.setYyyy(yyyy);
images.setUserid(u.getId()); images.setUserid(u.getId());
list = imgService.countByM(images); list = imgService.countByM(images);
} }
JSONArray json = JSONArray.parseArray("[{\"id\":1,\"monthNum\":\"一月\",\"countNum\":0},{\"id\":2,\"monthNum\":\"二月\",\"countNum\":0},{\"id\":3,\"monthNum\":\"三月\",\"countNum\":0},{\"id\":4,\"monthNum\":\"四月\",\"countNum\":0},{\"id\":5,\"monthNum\":\"五月\",\"countNum\":0},{\"id\":6,\"monthNum\":\"六月\",\"countNum\":0},{\"id\":7,\"monthNum\":\"七月\",\"countNum\":0},{\"id\":8,\"monthNum\":\"八月\",\"countNum\":0},{\"id\":9,\"monthNum\":\"九月\",\"countNum\":0},{\"id\":10,\"monthNum\":\"十月\",\"countNum\":0},{\"id\":11,\"monthNum\":\"十一月\",\"countNum\":0},{\"id\":12,\"monthNum\":\"十二月\",\"countNum\":0}]"); JSONArray json =
JSONArray.parseArray(
"[{\"id\":1,\"monthNum\":\"一月\",\"countNum\":0},{\"id\":2,\"monthNum\":\"二月\",\"countNum\":0},{\"id\":3,\"monthNum\":\"三月\",\"countNum\":0},{\"id\":4,\"monthNum\":\"四月\",\"countNum\":0},{\"id\":5,\"monthNum\":\"五月\",\"countNum\":0},{\"id\":6,\"monthNum\":\"六月\",\"countNum\":0},{\"id\":7,\"monthNum\":\"七月\",\"countNum\":0},{\"id\":8,\"monthNum\":\"八月\",\"countNum\":0},{\"id\":9,\"monthNum\":\"九月\",\"countNum\":0},{\"id\":10,\"monthNum\":\"十月\",\"countNum\":0},{\"id\":11,\"monthNum\":\"十一月\",\"countNum\":0},{\"id\":12,\"monthNum\":\"十二月\",\"countNum\":0}]");
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
for (int j = 0; j < list.size(); j++) { for (int j = 0; j < list.size(); j++) {
for (int i = 0; i < json.size(); i++) { for (int i = 0; i < json.size(); i++) {
JSONObject jobj = json.getJSONObject(i); JSONObject jobj = json.getJSONObject(i);
if(jobj.getInteger("id")==list.get(j).getMonthNum()){ if (jobj.getInteger("id") == list.get(j).getMonthNum()) {
jobj.put("monthNum",getChinaes(list.get(j).getMonthNum())); jobj.put("monthNum", getChinaes(list.get(j).getMonthNum()));
jobj.put("countNum",list.get(j).getCountNum()); jobj.put("countNum", list.get(j).getCountNum());
} }
} }
} }
@@ -257,7 +281,7 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping("/getStorage")//new @PostMapping("/getStorage")
@ResponseBody @ResponseBody
public Msg getStorage() { public Msg getStorage() {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -266,7 +290,7 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping("/getStorageName")//new @PostMapping("/getStorageName")
@ResponseBody @ResponseBody
public Msg getStorageName() { public Msg getStorageName() {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -275,7 +299,7 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping(value = "/selectPhoto")//new @PostMapping(value = {"/selectPhoto", "/client/selectPhoto"})
@ResponseBody @ResponseBody
public Msg selectPhoto(@RequestParam(value = "data", defaultValue = "") String data) { public Msg selectPhoto(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -284,21 +308,21 @@ public class AdminController {
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
Integer pageNum = jsonObj.getInteger("pageNum"); Integer pageNum = jsonObj.getInteger("pageNum");
Integer pageSize = jsonObj.getInteger("pageSize"); Integer pageSize = jsonObj.getInteger("pageSize");
String username = jsonObj.getString("username");
Integer source = jsonObj.getInteger("source"); Integer source = jsonObj.getInteger("source");
String starttime = jsonObj.getString("starttime"); String starttime = jsonObj.getString("starttime");
String stoptime = jsonObj.getString("stoptime"); String stoptime = jsonObj.getString("stoptime");
String selectUserType = jsonObj.getString("selectUserType"); // me/all
String username = jsonObj.getString("username");
Integer selecttype = jsonObj.getInteger("selecttype"); Integer selecttype = jsonObj.getInteger("selecttype");
String classifuids = jsonObj.getString("classifuids");
boolean violation = jsonObj.getBoolean("violation"); boolean violation = jsonObj.getBoolean("violation");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(starttime!=null){ if (starttime != null) {
try { try {
Date date1 = format.parse(starttime); Date date1 = format.parse(starttime);
Date date2 = format.parse(stoptime==null?format.format(new Date()):stoptime); Date date2 = format.parse(stoptime == null ? format.format(new Date()) : stoptime);
int compareTo = date1.compareTo(date2); int compareTo = date1.compareTo(date2);
System.out.println(compareTo); System.out.println(compareTo);
if(compareTo==1){ if (compareTo == 1) {
msg.setCode("110500"); msg.setCode("110500");
msg.setInfo("起始日期不能大于结束日期"); msg.setInfo("起始日期不能大于结束日期");
return msg; return msg;
@@ -312,46 +336,45 @@ public class AdminController {
} }
Images img = new Images(); Images img = new Images();
PageHelper.startPage(pageNum, pageSize); PageHelper.startPage(pageNum, pageSize);
if(violation){ if (violation) {
img.setViolation("true"); img.setViolation("true");
} }
img.setUsername(username);
img.setSource(source);
img.setSelecttype(selecttype);
img.setStarttime(starttime); img.setStarttime(starttime);
img.setStoptime(stoptime); img.setStoptime(stoptime);
if(classifuids!=null){ if (subject.hasRole("admin")) {
String[] calssif = classifuids.split(","); img.setSource(source);
img.setClassifuidlist(calssif); if (selectUserType.equals("me")) {
} img.setUserid(user.getId());
if(subject.hasRole("admin")){ img.setUsername(null);
//管理员 sql根据userid是否等于空做的判断, img.setSelecttype(null);
img.setUserid(null); } else {
}else{ img.setUsername(username);
//普通用户 img.setSelecttype(selecttype);
}
} else {
img.setUserid(user.getId()); img.setUserid(user.getId());
} }
List<Images> images = imgService.selectimg(img); List<Images> images = imgService.selectimg(img);
PageInfo<Images> rolePageInfo = new PageInfo<>(images); PageInfo<Images> rolePageInfo = new PageInfo<>(images);
PageResultBean<Images> pageResultBean = new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList()); PageResultBean<Images> pageResultBean =
new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList());
msg.setData(pageResultBean); msg.setData(pageResultBean);
return msg; return msg;
} }
@PostMapping(value = "/getUserInfo")
@PostMapping(value = "/getUserInfo") //new
@ResponseBody @ResponseBody
public Msg getUserInfo() { public Msg getUserInfo() {
Msg msg = new Msg(); Msg msg = new Msg();
try { try {
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
final User u = new User(); User u = new User();
u.setId(user.getId()); u.setId(user.getId());
User userInfo = userService.getUsers(u); User userInfo = userService.getUsers(u);
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("username",userInfo.getUsername()); jsonObject.put("username", userInfo.getUsername());
jsonObject.put("email",userInfo.getEmail()); jsonObject.put("email", userInfo.getEmail());
msg.setData(jsonObject); msg.setData(jsonObject);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -361,7 +384,7 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping("/setUserInfo") //new @PostMapping("/setUserInfo")
@ResponseBody @ResponseBody
public Msg setUserInfo(@RequestParam(value = "data", defaultValue = "") String data) { public Msg setUserInfo(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -373,46 +396,44 @@ public class AdminController {
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
User user = new User(); User user = new User();
if(!SetText.checkEmail(email)){ if (!SetText.checkEmail(email)) {
msg.setCode("110403"); msg.setCode("110403");
msg.setInfo("邮箱格式不正确"); msg.setInfo("邮箱格式不正确");
return msg; return msg;
} }
String regex = "^\\w+$"; String regex = "^\\w+$";
if(username.length()>20 || !username.matches (regex)){ if (username.length() > 20 || !username.matches(regex)) {
msg.setCode("110403"); msg.setCode("110403");
msg.setInfo("用户名不得超过20位字符"); msg.setInfo("用户名不得超过20位字符");
return msg; return msg;
} }
if(subject.hasRole("admin")){ if (subject.hasRole("admin")) {
final User userOld = new User(); User userOld = new User();
userOld.setId(u.getId()); userOld.setId(u.getId());
User userInfo = userService.getUsers(userOld); User userInfo = userService.getUsers(userOld);
if(!userInfo.getUsername().equals(username)){ if (!userInfo.getUsername().equals(username)) {
//要修改用户名
Integer countusername = userService.countusername(username); Integer countusername = userService.countusername(username);
if(countusername == 1 || !SysName.CheckSysName(username)){ if (countusername == 1 || !SysName.CheckSysName(username)) {
msg.setCode("110406"); msg.setCode("110406");
msg.setInfo("此用户名已存在"); msg.setInfo("此用户名已存在");
return msg; return msg;
}else { } else {
user.setUsername(username); user.setUsername(username);
} }
} }
if(!userInfo.getEmail().equals(email)){ if (!userInfo.getEmail().equals(email)) {
//要修改邮箱
Integer countmail = userService.countmail(email); Integer countmail = userService.countmail(email);
if(countmail == 1){ if (countmail == 1) {
msg.setCode("110407"); msg.setCode("110407");
msg.setInfo("此邮箱已被注册"); msg.setInfo("此邮箱已被注册");
return msg; return msg;
}else{ } else {
user.setEmail(email); user.setEmail(email);
} }
} }
user.setPassword(Base64Encryption.encryptBASE64(password.getBytes())); user.setPassword(Base64Encryption.encryptBASE64(password.getBytes()));
user.setUid(u.getUid()); user.setUid(u.getUid());
}else{ } else {
user.setPassword(Base64Encryption.encryptBASE64(password.getBytes())); user.setPassword(Base64Encryption.encryptBASE64(password.getBytes()));
user.setUid(u.getUid()); user.setUid(u.getUid());
} }
@@ -426,136 +447,133 @@ public class AdminController {
return msg; return msg;
} }
@PostMapping({"/deleImages", "/client/deleImages"})
@PostMapping("/deleImages") //new
@ResponseBody @ResponseBody
public Msg deleImages(@RequestParam(value = "data", defaultValue = "") String data) { public Msg deleImages(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
JSONArray images = jsonObj.getJSONArray("images"); String images = jsonObj.getString("images");
Subject subject = SecurityUtils.getSubject(); String uuid = jsonObj.getString("uuid");
User user = (User) subject.getPrincipal(); if (images == null) {
if(null == user){
msg.setCode("500");
msg.setInfo("当前用户信息不存在");
return msg;
}
if(images.size()==0){
msg.setCode("404"); msg.setCode("404");
msg.setInfo("为获取到图像信息"); msg.setInfo("为获取到图像信息");
return msg; return msg;
} }
for (int i = 0; i < images.size(); i++) { String[] split = images.split(",");
Integer imgid = images.getInteger(i); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
if (null == user) {
msg.setCode("500");
msg.setInfo("当前用户信息不存在");
return msg;
}
if (split.length == 0) {
msg.setCode("404");
msg.setInfo("为获取到图像信息");
return msg;
}
List<Long> imgIds = new ArrayList<Long>();
for (int i = 0; i < split.length; i++) {
Long imgid = Long.valueOf(split[i]);
Images image = imgService.selectByPrimaryKey(imgid); Images image = imgService.selectByPrimaryKey(imgid);
Integer keyid = image.getSource(); if (!subject.hasRole("admin")) {
String imgname = image.getImgname(); if (!image.getUserid().equals(user.getId())) {
Keys key = keysService.selectKeys(keyid);
if(!subject.hasRole("admin")){
if(image.getUserid()!=user.getId()){
break; break;
} }
} }
//删除图片 imgIds.add(imgid);
boolean isDele = false; }
try{ if (imgIds.size() == 0) {
if (key.getStorageType() == 1) { msg.setCode("110404");
isDele = nosImageupload.delNOS(key.getId(), imgname); } else {
} else if (key.getStorageType() == 2) { deleimages.dele(uuid, imgIds.stream().toArray(Long[]::new));
isDele = ossImageupload.delOSS(key.getId(), imgname); msg.setCode("200");
} else if (key.getStorageType() == 3) {
isDele = ussImageupload.delUSS(key.getId(), imgname);
} else if (key.getStorageType() == 4) {
isDele = kodoImageupload.delKODO(key.getId(), imgname);
} else if (key.getStorageType() == 5) {
isDele = LocUpdateImg.deleteLOCImg(imgname);
}else if (key.getStorageType() == 6) {
isDele = cosImageupload.delCOS(key.getId(), imgname);
}else if (key.getStorageType() == 7) {
isDele = ftpImageupload.delFTP(key.getId(), imgname);
}else if (key.getStorageType() == 8) {
isDele = uFileImageupload.delUFile(key.getId(), imgname);
}else {
System.err.println("未获取到对象存储参数,删除失败。");
}
}catch (Exception e){
e.printStackTrace();
}
//删除库
if(isDele){
try {
//删除图像表之前先删除临时数据表,图像表也会删除
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(imgid);
imgAndAlbumService.deleteImgAndAlbum(imgname);
} catch (Exception e) {
e.printStackTrace();
msg.setInfo("图片记录删除失败,请重试");
msg.setCode("500");
return msg;
}
msg.setInfo("删除成功");
}else{
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(imgid);
imgAndAlbumService.deleteImgAndAlbum(imgname);
msg.setInfo("图片记录已删除,但是图片源删除失败");
}
} }
System.out.println("返回的值:"+msg.toString());
return msg; return msg;
} }
@PostMapping({"/GetDelprogress", "/client/GetDelprogress"})
//工具函数 @ResponseBody
private static String getChinaes(int v){ public Msg GetDelprogress(@RequestParam(value = "data", defaultValue = "") String data) {
String ch = ""; Msg msg = new Msg();
switch(v){ try {
case 1 : JSONObject jsonObj = JSONObject.parseObject(data);
ch = "一月"; String uuid = jsonObj.getString("uuid");
break; //可选 JSONObject jsonObject = new JSONObject();
case 2 : MyProgress myProgress = null;
ch = "二月"; try{
break; //可选 myProgress = JSON.parseObject(iRedisService.getValue(uuid).toString(), MyProgress.class);
case 3 : }catch (Exception e){ }
ch = "三月"; msg.setCode("110666");
break; //可选 msg.setInfo("正在执行");
case 4 : if (null == myProgress) {
ch = "四月"; jsonObject.put("succ", 0);
break; //可选 jsonObject.put("errorlist", new ArrayList<String>());
case 5 : jsonObject.put("oklist", new ArrayList<Long>());
ch = "五月"; jsonObject.put("delover", false);
break; //可选 } else {
case 6 : jsonObject.put("succ", myProgress.getDelSuccessCount());
ch = "六月"; jsonObject.put("errorlist", myProgress.getDelErrorImgListt());
break; //可选 jsonObject.put("oklist", myProgress.getDelSuccessImgList());
case 7 : jsonObject.put("delover", myProgress.getDelOCT());
ch = "七月"; if(myProgress.getDelOCT()==1){
break; //可选 System.out.println("循环遍历的值:"+myProgress.getDelOCT());
case 8 : msg.setCode("100");
ch = "八月"; }
break; //可选 }
case 9 : msg.setData(jsonObject);
ch = "九月"; return msg;
break; //可选 } catch (Exception e) {
case 10 : e.printStackTrace();
ch = "十月"; msg.setCode("110500");
break; //可选 msg.setInfo("正在执行过程中发生错误");
case 11 : return msg;
ch = "十一月";
break; //可选
case 12 :
ch = "十二月";
break; //可选
default : ch = "";//可选
//语句
} }
return ch;
} }
private static String getChinaes(int v) {
String ch = "";
switch (v) {
case 1:
ch = "一月";
break; // 可选
case 2:
ch = "二月";
break; // 可选
case 3:
ch = "三月";
break; // 可选
case 4:
ch = "四月";
break; // 可选
case 5:
ch = "五月";
break; // 可选
case 6:
ch = "六月";
break; // 可选
case 7:
ch = "七月";
break; // 可选
case 8:
ch = "八月";
break; // 可选
case 9:
ch = "九月";
break; // 可选
case 10:
ch = "十月";
break; // 可选
case 11:
ch = "十一月";
break; // 可选
case 12:
ch = "十二月";
break; // 可选
default:
ch = ""; // 可选
// 语句
}
return ch;
}
} }
@@ -3,8 +3,8 @@ package cn.hellohao.controller;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.service.*; import cn.hellohao.service.*;
import cn.hellohao.service.impl.*; import cn.hellohao.service.impl.*;
import cn.hellohao.utils.*; import cn.hellohao.utils.NewSendEmail;
import cn.hutool.http.HttpUtil; import cn.hellohao.utils.SetFiles;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
@@ -13,27 +13,19 @@ import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
@Controller @Controller
@RequestMapping("/admin/root") @RequestMapping("/admin/root")
public class AdminRootController { public class AdminRootController {
@Autowired @Autowired
private NOSImageupload nOSImageupload; private ConfdataService confdataService;
@Autowired
private ConfigService configService;
@Autowired @Autowired
private KeysService keysService; private KeysService keysService;
@Autowired @Autowired
@@ -43,40 +35,40 @@ public class AdminRootController {
@Autowired @Autowired
private UploadConfigService uploadConfigService; private UploadConfigService uploadConfigService;
@Autowired @Autowired
private NoticeService noticeService;
@Autowired
private SysConfigService sysConfigService; private SysConfigService sysConfigService;
@Autowired @Autowired
private GroupService groupService;
@Autowired
private ImgService imgService; private ImgService imgService;
@Autowired @Autowired
private ImgreviewService imgreviewService; private ImgreviewService imgreviewService;
@Autowired
private AppClientService appClientService;
@PostMapping(value = "/getUserList")//new @PostMapping(value = "/getUserList")
@ResponseBody @ResponseBody
public Map<String, Object> getUserList(@RequestParam(value = "data", defaultValue = "") String data) { public Msg getUserList(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObj = JSONObject.parseObject(data); Msg msg = new Msg();
Integer pageNum = jsonObj.getInteger("pageNum"); try{
Integer pageSize = jsonObj.getInteger("pageSize"); JSONObject jsonObj = JSONObject.parseObject(data);
String queryText = jsonObj.getString("queryText"); Integer pageNum = jsonObj.getInteger("pageNum");
PageHelper.startPage(pageNum, pageSize); Integer pageSize = jsonObj.getInteger("pageSize");
List<User> users = userService.getuserlist(queryText); String queryText = jsonObj.getString("queryText");
PageInfo<User> rolePageInfo = new PageInfo<>(users); PageHelper.startPage(pageNum, pageSize);
Map<String, Object> map = new HashMap<String, Object>(); List<User> users = userService.getuserlist(queryText);
map.put("count", rolePageInfo.getTotal()); PageInfo<User> rolePageInfo = new PageInfo<>(users);
map.put("users", rolePageInfo.getList()); msg.setData(rolePageInfo);
return map; }catch (Exception e){
msg.setCode("500");
}
return msg;
} }
@PostMapping(value = "/updateUserInfo")//new @PostMapping(value = "/updateUserInfo")
@ResponseBody @ResponseBody
public Msg updateUserInfo(@RequestParam(value = "data", defaultValue = "") String data) { public Msg updateUserInfo(@RequestParam(value = "data", defaultValue = "") String data) {
final Msg msg = new Msg(); final Msg msg = new Msg();
try{ try {
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
@@ -85,7 +77,7 @@ public class AdminRootController {
Long memory = jsonObj.getLong("memory"); Long memory = jsonObj.getLong("memory");
Integer groupid = jsonObj.getInteger("groupid"); Integer groupid = jsonObj.getInteger("groupid");
Integer isok = jsonObj.getInteger("isok"); Integer isok = jsonObj.getInteger("isok");
if(memory<0 || memory>1048576L){ if (memory < 0 || memory > 1048576L) {
msg.setCode("500"); msg.setCode("500");
msg.setInfo("容量不得超过1048576"); msg.setInfo("容量不得超过1048576");
return msg; return msg;
@@ -96,14 +88,14 @@ public class AdminRootController {
User userInfo = userService.getUsers(user2); User userInfo = userService.getUsers(user2);
user.setId(id); user.setId(id);
user.setEmail(email); user.setEmail(email);
user.setMemory(Long.toString(memory*1024*1024)); user.setMemory(Long.toString(memory * 1024 * 1024));
user.setGroupid(groupid); user.setGroupid(groupid);
if(userInfo.getLevel()==1){ if (userInfo.getLevel() == 1) {
user.setIsok(isok==1?1:-1); user.setIsok(isok == 1 ? 1 : -1);
} }
userService.changeUser(user); userService.changeUser(user);
msg.setInfo("修改成功"); msg.setInfo("修改成功");
}catch (Exception e){ } catch (Exception e) {
msg.setCode("500"); msg.setCode("500");
msg.setInfo("修改失败"); msg.setInfo("修改失败");
e.printStackTrace(); e.printStackTrace();
@@ -112,7 +104,7 @@ public class AdminRootController {
} }
@PostMapping("/disableUser")//new @PostMapping("/disableUser")
@ResponseBody @ResponseBody
public Msg disableUser(@RequestParam(value = "data", defaultValue = "") String data) { public Msg disableUser(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -123,7 +115,7 @@ public class AdminRootController {
User u = new User(); User u = new User();
u.setId(userIdList.getInteger(i)); u.setId(userIdList.getInteger(i));
User u2 = userService.getUsers(u); User u2 = userService.getUsers(u);
if(u2.getLevel()==1){ if (u2.getLevel() == 1) {
User user = new User(); User user = new User();
user.setId(userIdList.getInteger(i)); user.setId(userIdList.getInteger(i));
user.setIsok(-1); user.setIsok(-1);
@@ -132,7 +124,7 @@ public class AdminRootController {
} }
msg.setInfo("所选用户已被禁用"); msg.setInfo("所选用户已被禁用");
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setInfo("系统错误"); msg.setInfo("系统错误");
msg.setCode("500"); msg.setCode("500");
@@ -140,7 +132,7 @@ public class AdminRootController {
return msg; return msg;
} }
@PostMapping("/deleUser")//new @PostMapping("/deleUser")
@ResponseBody @ResponseBody
public Msg deleuser(@RequestParam(value = "data", defaultValue = "") String data) { public Msg deleuser(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -152,18 +144,18 @@ public class AdminRootController {
User u = new User(); User u = new User();
u.setId(userIdList.getInteger(i)); u.setId(userIdList.getInteger(i));
User user = userService.getUsers(u); User user = userService.getUsers(u);
if(user.getLevel()==1){ if (user.getLevel() == 1) {
userService.deleuser(userIdList.getInteger(i)); userService.deleuser(userIdList.getInteger(i));
}else{ } else {
b = true; b = true;
} }
} }
if(b && userIdList.size()==1){ if (b && userIdList.size() == 1) {
msg.setInfo("管理员账户不可删除"); msg.setInfo("管理员账户不可删除");
}else { } else {
msg.setInfo("用户已删除成功"); msg.setInfo("用户已删除成功");
} }
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setInfo("系统错误"); msg.setInfo("系统错误");
msg.setCode("500"); msg.setCode("500");
@@ -171,7 +163,7 @@ public class AdminRootController {
return msg; return msg;
} }
@PostMapping("/getKeysList") //new @PostMapping("/getKeysList")
@ResponseBody @ResponseBody
public Msg getKeysList() { public Msg getKeysList() {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -180,7 +172,7 @@ public class AdminRootController {
return msg; return msg;
} }
@PostMapping("/LoadInfo")//new @PostMapping("/LoadInfo")
@ResponseBody @ResponseBody
public Msg LoadInfo(@RequestParam(value = "data", defaultValue = "") String data) { public Msg LoadInfo(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -188,34 +180,34 @@ public class AdminRootController {
JSONObject jsonData = JSONObject.parseObject(data); JSONObject jsonData = JSONObject.parseObject(data);
Integer keyId = jsonData.getInteger("keyId"); Integer keyId = jsonData.getInteger("keyId");
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("id",keyId); jsonObject.put("id", keyId);
Keys key = keysService.selectKeys(keyId); Keys key = keysService.selectKeys(keyId);
Integer ret = 0; Integer ret = 0;
if(key.getStorageType()==1){ if (key.getStorageType() == 1) {
ret = NOSImageupload.Initialize(key); ret = NOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){ } else if (key.getStorageType() == 2) {
ret = OSSImageupload.Initialize(key); ret = OSSImageupload.Initialize(key);
}else if(key.getStorageType()==3){ } else if (key.getStorageType() == 3) {
ret = USSImageupload.Initialize(key); ret = USSImageupload.Initialize(key);
}else if(key.getStorageType()==4){ } else if (key.getStorageType() == 4) {
ret = KODOImageupload.Initialize(key); ret = KODOImageupload.Initialize(key);
}else if(key.getStorageType()==6){ } else if (key.getStorageType() == 6) {
ret = COSImageupload.Initialize(key); ret = COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){ } else if (key.getStorageType() == 7) {
ret = FTPImageupload.Initialize(key); ret = FtpServiceImpl.Initialize(key);
}else if(key.getStorageType()==8){ } else if (key.getStorageType() == 8) {
ret = UFileImageupload.Initialize(key); ret = S3Imageupload.Initialize(key);
} }
Long l = imgService.getsourcememory(keyId); Long l = imgService.getsourcememory(keyId);
jsonObject.put("isok",ret); jsonObject.put("isok", ret);
jsonObject.put("storagetype",key.getStorageType()); jsonObject.put("storagetype", key.getStorageType());
if(l==null){ if (l == null) {
jsonObject.put("usedCapacity",0); jsonObject.put("usedCapacity", 0);
}else{ } else {
jsonObject.put("usedCapacity", SetFiles.readableFileSize(l)); jsonObject.put("usedCapacity", SetFiles.readableFileSize(l));
} }
msg.setData(jsonObject); msg.setData(jsonObject);
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setCode("500"); msg.setCode("500");
} }
@@ -223,32 +215,33 @@ public class AdminRootController {
} }
@PostMapping("/updateStorage") //new @PostMapping("/updateStorage")
@ResponseBody @ResponseBody
public Msg updateStorage(@RequestParam(value = "data", defaultValue = "") String data) { public Msg updateStorage(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
Integer id = jsonObj.getInteger("id"); // Integer id = jsonObj.getInteger("id");
String AccessKey = jsonObj.getString("AccessKey"); // String AccessKey = jsonObj.getString("AccessKey");
String AccessSecret = jsonObj.getString("AccessSecret"); // String AccessSecret = jsonObj.getString("AccessSecret");
String Endpoint = jsonObj.getString("Endpoint"); // String Endpoint = jsonObj.getString("Endpoint");
String Bucketname = jsonObj.getString("Bucketname"); // String Bucketname = jsonObj.getString("Bucketname");
String RequestAddress = jsonObj.getString("RequestAddress"); // String RequestAddress = jsonObj.getString("RequestAddress");
Integer storageType = jsonObj.getInteger("storageType"); // Integer storageType = jsonObj.getInteger("storageType");
String keyname = jsonObj.getString("keyname"); // String keyname = jsonObj.getString("keyname");
Keys keys = new Keys(); // Keys keys = new Keys();
keys.setId(id); // keys.setId(id);
keys.setAccessKey(AccessKey); // keys.setAccessKey(AccessKey);
keys.setAccessSecret(AccessSecret); // keys.setAccessSecret(AccessSecret);
keys.setEndpoint(Endpoint); // keys.setEndpoint(Endpoint);
keys.setBucketname(Bucketname); // keys.setBucketname(Bucketname);
keys.setRequestAddress(RequestAddress); // keys.setRequestAddress(RequestAddress);
keys.setStorageType(storageType); // keys.setStorageType(storageType);
keys.setKeyname(keyname); // keys.setKeyname(keyname);
Keys keys = JSON.toJavaObject(jsonObj,Keys.class);
Msg msg = keysService.updateKey(keys); Msg msg = keysService.updateKey(keys);
return msg; return msg;
} }
@PostMapping("/getStorageById")//new @PostMapping("/getStorageById")
@ResponseBody @ResponseBody
public Msg getselectkey(@RequestParam(value = "data", defaultValue = "") String data) { public Msg getselectkey(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -259,8 +252,7 @@ public class AdminRootController {
return msg; return msg;
} }
@PostMapping("/getSettingConfig")
@PostMapping("/getSettingConfig") //new
@ResponseBody @ResponseBody
public Msg getSettingConfig(@RequestParam(value = "data", defaultValue = "") String data) { public Msg getSettingConfig(@RequestParam(value = "data", defaultValue = "") String data) {
final Msg msg = new Msg(); final Msg msg = new Msg();
@@ -269,15 +261,17 @@ public class AdminRootController {
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
try { try {
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
Config config = configService.getSourceype(); final Confdata confdata = confdataService.selectConfdata("config");
SysConfig sysConfig = sysConfigService.getstate(); SysConfig sysConfig = sysConfigService.getstate();
uploadConfig.setUsermemory(Long.toString(Long.valueOf(uploadConfig.getUsermemory())/1024/1024)); AppClient appClientData = appClientService.getAppClientData("app");
uploadConfig.setVisitormemory(Long.toString(Long.valueOf(uploadConfig.getVisitormemory())/1024/1024)); uploadConfig.setUsermemory(Long.toString(Long.valueOf(uploadConfig.getUsermemory()) / 1024 / 1024));
uploadConfig.setFilesizetourists(Long.toString(Long.valueOf(uploadConfig.getFilesizetourists())/1024/1024)); uploadConfig.setVisitormemory(Long.toString(Long.valueOf(uploadConfig.getVisitormemory()) / 1024 / 1024));
uploadConfig.setFilesizeuser(Long.toString(Long.valueOf(uploadConfig.getFilesizeuser())/1024/1024)); uploadConfig.setFilesizetourists(Long.toString(Long.valueOf(uploadConfig.getFilesizetourists()) / 1024 / 1024));
jsonObject.put("uploadConfig",uploadConfig); uploadConfig.setFilesizeuser(Long.toString(Long.valueOf(uploadConfig.getFilesizeuser()) / 1024 / 1024));
jsonObject.put("config",config); jsonObject.put("uploadConfig", uploadConfig);
jsonObject.put("sysConfig",sysConfig); jsonObject.put("config", JSONObject.parseObject(confdata.getJsondata()));
jsonObject.put("sysConfig", sysConfig);
jsonObject.put("appClient", appClientData);
msg.setData(jsonObject); msg.setData(jsonObject);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -288,36 +282,44 @@ public class AdminRootController {
} }
@PostMapping("/updateConfig")//new @PostMapping("/updateConfig")
@ResponseBody @ResponseBody
public Msg updateConfig(@RequestParam(value = "data", defaultValue = "") String data) { public Msg updateConfig(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
try { try {
JSONObject jsonObject = JSONObject.parseObject(data); JSONObject jsonObject = JSONObject.parseObject(data);
UploadConfig uploadConfig = JSON.toJavaObject((JSON) jsonObject.get("uploadConfig"),UploadConfig.class); UploadConfig uploadConfig = JSON.toJavaObject((JSON) jsonObject.get("uploadConfig"), UploadConfig.class);
String vm = uploadConfig.getVisitormemory(); String vm = uploadConfig.getVisitormemory();
if((Long.valueOf(vm)<-1) || Long.valueOf(vm) > 104857600 || Long.valueOf(uploadConfig.getFilesizetourists())<0 || Long.valueOf(uploadConfig.getFilesizetourists()) > 5120 if ((Long.valueOf(vm) < -1) || Long.valueOf(vm) > 104857600 || Long.valueOf(uploadConfig.getFilesizetourists()) < 0 || Long.valueOf(uploadConfig.getFilesizetourists()) > 5120
|| Long.valueOf(uploadConfig.getUsermemory())<0 || Long.valueOf(uploadConfig.getUsermemory())>1048576 || Long.valueOf(uploadConfig.getUsermemory()) < 0 || Long.valueOf(uploadConfig.getUsermemory()) > 1048576
|| Long.valueOf(uploadConfig.getFilesizeuser())<0 || Long.valueOf(uploadConfig.getFilesizeuser())>5120 ){ || Long.valueOf(uploadConfig.getFilesizeuser()) < 0 || Long.valueOf(uploadConfig.getFilesizeuser()) > 5120) {
msg.setInfo("你输入的值不正确"); msg.setInfo("你输入的值不正确");
msg.setCode("500"); msg.setCode("500");
return msg; return msg;
} }
Config config = JSON.toJavaObject((JSON) jsonObject.get("config"),Config.class); // Config config = JSON.toJavaObject((JSON) jsonObject.get("config"), Config.class);
SysConfig sysConfig = JSON.toJavaObject((JSON) jsonObject.get("sysConfig"),SysConfig.class); SysConfig sysConfig = JSON.toJavaObject((JSON) jsonObject.get("sysConfig"), SysConfig.class);
if(Integer.valueOf(vm)==-1){ AppClient appClient = JSON.toJavaObject((JSON) jsonObject.get("appClient"), AppClient.class);
if (Integer.valueOf(vm) == -1) {
uploadConfig.setVisitormemory("-1"); uploadConfig.setVisitormemory("-1");
}else{ } else {
uploadConfig.setVisitormemory(Long.toString(Long.valueOf(uploadConfig.getVisitormemory())*1024*1024)); uploadConfig.setVisitormemory(Long.toString(Long.valueOf(uploadConfig.getVisitormemory()) * 1024 * 1024));
} }
uploadConfig.setFilesizetourists(Long.toString(Long.valueOf(uploadConfig.getFilesizetourists())*1024*1024)); uploadConfig.setFilesizetourists(Long.toString(Long.valueOf(uploadConfig.getFilesizetourists()) * 1024 * 1024));
uploadConfig.setUsermemory(Long.toString(Long.valueOf(uploadConfig.getUsermemory())*1024*1024)); uploadConfig.setUsermemory(Long.toString(Long.valueOf(uploadConfig.getUsermemory()) * 1024 * 1024));
uploadConfig.setFilesizeuser(Long.toString(Long.valueOf(uploadConfig.getFilesizeuser())*1024*1024)); uploadConfig.setFilesizeuser(Long.toString(Long.valueOf(uploadConfig.getFilesizeuser()) * 1024 * 1024));
uploadConfigService.setUpdateConfig(uploadConfig); uploadConfigService.setUpdateConfig(uploadConfig);
configService.setSourceype(config); Confdata confdata = new Confdata();
confdata.setKey("config");
confdata.setJsondata(jsonObject.getJSONObject("config").toJSONString());
confdataService.updateConfdata(confdata);
sysConfigService.setstate(sysConfig); sysConfigService.setstate(sysConfig);
if (!appClient.getIsuse().equals("on")) {
appClient.setIsuse("off");
}
appClientService.editAppClientData(appClient);
msg.setInfo("配置保存成功"); msg.setInfo("配置保存成功");
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setInfo("操作出现异常"); msg.setInfo("操作出现异常");
msg.setCode("500"); msg.setCode("500");
@@ -326,7 +328,7 @@ public class AdminRootController {
} }
@PostMapping(value = "/getOrderConfig")//new @PostMapping(value = "/getOrderConfig")
@ResponseBody @ResponseBody
public Msg emailconfig() { public Msg emailconfig() {
final Msg msg = new Msg(); final Msg msg = new Msg();
@@ -336,8 +338,8 @@ public class AdminRootController {
final JSONObject jsonObject = new JSONObject(); final JSONObject jsonObject = new JSONObject();
emailConfig = emailConfigService.getemail(); emailConfig = emailConfigService.getemail();
imgreview = imgreviewService.selectByPrimaryKey(1); imgreview = imgreviewService.selectByPrimaryKey(1);
jsonObject.put("emailConfig",emailConfig); jsonObject.put("emailConfig", emailConfig);
jsonObject.put("imgreview",imgreview); jsonObject.put("imgreview", imgreview);
msg.setData(jsonObject); msg.setData(jsonObject);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -348,17 +350,17 @@ public class AdminRootController {
} }
@PostMapping("/updateEmailConfig") //new @PostMapping("/updateEmailConfig")
@ResponseBody @ResponseBody
public Msg updateemail(@RequestParam(value = "data", defaultValue = "") String data ) { public Msg updateemail(@RequestParam(value = "data", defaultValue = "") String data) {
final Msg msg = new Msg(); final Msg msg = new Msg();
try { try {
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
EmailConfig emailConfig = JSON.toJavaObject(jsonObj,EmailConfig.class); EmailConfig emailConfig = JSON.toJavaObject(jsonObj, EmailConfig.class);
if(null==emailConfig.getId() || null==emailConfig.getEmailname() || null==emailConfig.getEmailurl() || null==emailConfig.getEmails() if (null == emailConfig.getId() || null == emailConfig.getEmailname() || null == emailConfig.getEmailurl() || null == emailConfig.getEmails()
|| null==emailConfig.getEmailkey() || null==emailConfig.getPort() || null==emailConfig.getUsing() || null == emailConfig.getEmailkey() || null == emailConfig.getPort() || null == emailConfig.getUsing()
|| emailConfig.getEmailname().equals("") || emailConfig.getEmailurl().equals("") || emailConfig.getEmails().equals("") || emailConfig.getEmailname().equals("") || emailConfig.getEmailurl().equals("") || emailConfig.getEmails().equals("")
|| emailConfig.getEmailkey().equals("") || emailConfig.getPort().equals("")){ || emailConfig.getEmailkey().equals("") || emailConfig.getPort().equals("")) {
msg.setCode("110400"); msg.setCode("110400");
msg.setInfo("各参数不能为空"); msg.setInfo("各参数不能为空");
return msg; return msg;
@@ -373,19 +375,18 @@ public class AdminRootController {
return msg; return msg;
} }
@PostMapping("/mailTest") //new @PostMapping("/mailTest")
@ResponseBody @ResponseBody
public Msg mailTest(@RequestParam(value = "data", defaultValue = "") String data ) { public Msg mailTest(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
String tomail = jsonObj.getString("tomail"); String tomail = jsonObj.getString("tomail");
EmailConfig emailConfig = JSON.toJavaObject(jsonObj,EmailConfig.class); EmailConfig emailConfig = JSON.toJavaObject(jsonObj, EmailConfig.class);
if(null==emailConfig.getEmails() || null==emailConfig.getEmailkey() || null==emailConfig.getEmailurl() if (null == emailConfig.getEmails() || null == emailConfig.getEmailkey() || null == emailConfig.getEmailurl()
|| null==emailConfig.getPort() || null==emailConfig.getEmailname() || null==tomail){ || null == emailConfig.getPort() || null == emailConfig.getEmailname() || null == tomail) {
// if(jsonObj.size()==0){
msg.setCode("110400"); msg.setCode("110400");
msg.setInfo("邮箱配置参数不能为空"); msg.setInfo("邮箱配置参数不能为空");
}else{ } else {
msg = NewSendEmail.sendTestEmail(emailConfig, tomail); msg = NewSendEmail.sendTestEmail(emailConfig, tomail);
} }
return msg; return msg;
@@ -2,7 +2,8 @@ package cn.hellohao.controller;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.pojo.vo.PageResultBean; import cn.hellohao.pojo.vo.PageResultBean;
import cn.hellohao.service.*; import cn.hellohao.service.ImgAndAlbumService;
import cn.hellohao.service.UserService;
import cn.hellohao.service.impl.AlbumServiceImpl; import cn.hellohao.service.impl.AlbumServiceImpl;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
@@ -13,10 +14,10 @@ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
@@ -30,23 +31,17 @@ public class AlbumController {
@Autowired @Autowired
AlbumServiceImpl albumServiceImpl; AlbumServiceImpl albumServiceImpl;
@Autowired @Autowired
private ConfigService configService;
@Autowired
private ImgService imgService;
@Autowired
ImgAndAlbumService imgAndAlbumService; ImgAndAlbumService imgAndAlbumService;
@Autowired @Autowired
private UploadConfigService uploadConfigService;
@Autowired
private UserService userService; private UserService userService;
@PostMapping("/admin/getGalleryList") //new @PostMapping("/admin/getGalleryList")
@ResponseBody @ResponseBody
public Map<String, Object> getGalleryList (@RequestParam(value = "data", defaultValue = "") String data){ public Msg getGalleryList (@RequestParam(value = "data", defaultValue = "") String data){
Msg msg = new Msg();
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
user = userService.getUsers(user); user = userService.getUsers(user);
Map<String, Object> map = new HashMap<String, Object>();
Album album = new Album(); Album album = new Album();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
Integer pageNum = jsonObj.getInteger("pageNum"); Integer pageNum = jsonObj.getInteger("pageNum");
@@ -61,20 +56,17 @@ public class AlbumController {
try { try {
albums = albumServiceImpl.selectAlbumURLList(album); albums = albumServiceImpl.selectAlbumURLList(album);
PageInfo<Album> rolePageInfo = new PageInfo<>(albums); PageInfo<Album> rolePageInfo = new PageInfo<>(albums);
map.put("code", 200); msg.setData(rolePageInfo);
map.put("info", "");
map.put("count", rolePageInfo.getTotal());
map.put("data", rolePageInfo.getList());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
map.put("code", 500); msg.setInfo("获取数据异常");
map.put("info", "获取数据异常"); msg.setCode("500");
} }
return map; return msg;
} }
@PostMapping("/admin/deleGallery") //new 删除画廊 @PostMapping("/admin/deleGallery")
@ResponseBody @ResponseBody
public Msg deleGallery (@RequestParam(value = "data", defaultValue = "") String data) { public Msg deleGallery (@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -105,7 +97,39 @@ public class AlbumController {
} }
@PostMapping("/getAlbumImgList") //new //后台列表要修改时的查询表单
@PostMapping("/admin/getAlbumListForKey")
@ResponseBody
public Msg getAlbumListForKey(@RequestParam(value = "data", defaultValue = "") String data){
Msg msg = new Msg();
try{
JSONObject jsonObject = JSONObject.parseObject(data);
String key = jsonObject.getString("key");
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
Album album = new Album();
album.setAlbumkey(key);
if(subject.hasRole("admin")){
album.setUserid(null);
}else{
album.setUserid(user.getId());
}
JSONObject jsonObj = new JSONObject();
Album album1 = albumServiceImpl.selectAlbum(album);
List<Images> imagesList = imgAndAlbumService.selectImgForAlbumkey(key);
jsonObj.put("album",album1);
jsonObj.put("imagesList",imagesList);
msg.setData(jsonObj);
}catch (Exception e){
e.printStackTrace();
msg.setCode("500");
msg.setInfo("获取画廊数据错误");
}
return msg;
}
@PostMapping("/getAlbumImgList")
@ResponseBody @ResponseBody
public Msg getAlbumImgList(@RequestParam("data") String data) { public Msg getAlbumImgList(@RequestParam("data") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -116,7 +140,7 @@ public class AlbumController {
return msg; return msg;
} }
@PostMapping("/SaveForAlbum")//new @PostMapping("/SaveForAlbum")
@ResponseBody @ResponseBody
public Msg SaveForAlbum(@RequestParam(value = "data", defaultValue = "") String data){ public Msg SaveForAlbum(@RequestParam(value = "data", defaultValue = "") String data){
data = StringEscapeUtils.unescapeHtml4(data); data = StringEscapeUtils.unescapeHtml4(data);
@@ -141,7 +165,7 @@ public class AlbumController {
} }
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
String uuid = "TOALBUM"+ UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5)+"N"; String uuid = "TOALBUM"+ UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,7)+"N";
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Album album = new Album(); Album album = new Album();
album.setAlbumtitle(albumtitle); album.setAlbumtitle(albumtitle);
@@ -178,7 +202,66 @@ public class AlbumController {
} }
@PostMapping("/checkPass")//new @PostMapping("/admin/UpdateForAlbum")
@ResponseBody
public Msg UpdateForAlbum(@RequestParam(value = "data", defaultValue = "") String data){
data = StringEscapeUtils.unescapeHtml4(data);
Msg msg = new Msg();
try {
JSONObject jsonObject = JSONObject.parseObject(data);
String albumkey = jsonObject.getString("albumkey");
String albumtitle = jsonObject.getString("albumtitle");
String password = jsonObject.getString("password");
JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("albumlist"));
if(null!=password){
// String regex = "^[a-z0-9A-Z\u4e00-\u9fa5]+$";
// return str.matches(regex);
password = password.replace(" ", "");
if(password.replace(" ", "").equals("") || password.length()<3){
msg.setCode("110403");
msg.setInfo("密码长度不得小于三位有效字符");
return msg;
}
}
if(albumtitle==null || jsonArray.size()==0){
msg.setCode("110404");
msg.setInfo("标题和图片参数不能为空");
return msg;
}
Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal();
Album album = new Album();
album.setAlbumtitle(albumtitle);
album.setPassword(password);
album.setAlbumkey(albumkey);
albumServiceImpl.updateAlbum(album);
imgAndAlbumService.deleteImgAndAlbumForKey(albumkey);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject img = jsonArray.getJSONObject(i);
ImgAndAlbum imgAndAlbum = new ImgAndAlbum();
imgAndAlbum.setImgname(img.getString("imgurl"));
imgAndAlbum.setAlbumkey(albumkey);
imgAndAlbum.setNotes(img.getString("notes"));
albumServiceImpl.addAlbumForImgAndAlbumMapper(imgAndAlbum);
}
final JSONObject json = new JSONObject();
json.put("url",albumkey);
json.put("title",albumtitle);
json.put("password",password);
msg.setCode("200");
msg.setInfo("画廊修改成功");
msg.setData(json);
}catch (Exception e){
e.printStackTrace();
msg.setCode("500");
msg.setInfo("修改画廊失败");
}
return msg;
}
@PostMapping("/checkPass")
@ResponseBody @ResponseBody
public Msg checkPass(@RequestParam(value = "data", defaultValue = "") String data) { public Msg checkPass(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -212,7 +295,7 @@ public class AlbumController {
return msg; return msg;
} }
@PostMapping("/getAlbumList") //new @PostMapping("/getAlbumList")
@ResponseBody @ResponseBody
public Msg getAlbumList(@RequestParam(value = "data", defaultValue = "") String data){ public Msg getAlbumList(@RequestParam(value = "data", defaultValue = "") String data){
Msg msg = new Msg(); Msg msg = new Msg();
@@ -0,0 +1,125 @@
package cn.hellohao.controller;
import cn.hellohao.auth.token.JWTUtil;
import cn.hellohao.pojo.Msg;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.pojo.User;
import cn.hellohao.service.AppClientService;
import cn.hellohao.service.ImgService;
import cn.hellohao.service.UploadConfigService;
import cn.hellohao.service.impl.UploadServicel;
import cn.hellohao.service.impl.UserServiceImpl;
import cn.hellohao.utils.Base64ToMultipartFile;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
/**
* @author Hellohao
* @version 1.0
* @date 2022-05-16 32:45
*/
@RestController
@RequestMapping("/client")
public class ClientAppController {
@Autowired
private ImgService imgService;
@Autowired
private AppClientService appClientService;
@Autowired
private UserServiceImpl userService;
@Autowired
private UploadConfigService uploadConfigService;
@Autowired
private UploadServicel uploadServicel;
@PostMapping("/loginByToken")
@ResponseBody
public Msg loginByToken(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg();
try{
JSONObject jsonObj = JSONObject.parseObject(data);
JSONObject jsonObject = new JSONObject();
User newUser = new User();
String userToken = jsonObj.getString("userToken");
newUser.setToken(userToken);
User userData = userService.loginByToken(userToken);
if(userData.getIsok()<1){
SecurityUtils.getSubject().logout();
msg.setInfo("账号暂时无法使用,请咨询管理员");
msg.setCode("110403");
return msg;
}
String jwtToken = JWTUtil.createToken(userData);
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
jsonObject.put("username", userData.getUsername());
jsonObject.put("jwttoken", jwtToken);
jsonObject.put("suffix",uploadConfig.getSuffix().split(","));
jsonObject.put("myImgTotal", imgService.countimg(userData.getId()));
jsonObject.put("filesize",Integer.valueOf(uploadConfig.getFilesizeuser())/1024);
jsonObject.put("imgcount",uploadConfig.getImgcountuser());
jsonObject.put("uploadSwitch",uploadConfig.getUserclose());
long memory = Long.valueOf(userData.getMemory());
Long usermemory = imgService.getusermemory(userData.getId())==null?0L:imgService.getusermemory(userData.getId());
if(memory==0){
jsonObject.put("myMemory","无容量");
}else{
Double aDouble = Double.valueOf(String.format("%.2f", (((double)usermemory/(double)memory)*100)));
if(aDouble>=999){
jsonObject.put("myMemory",999);
}else{
jsonObject.put("myMemory",aDouble);
}
}
msg.setData(jsonObject);
}catch (Exception e){
e.printStackTrace();
msg.setCode("110500");
msg.setInfo("未获取到用户,请先在设置中添加Token");
}
return msg;
}
@PostMapping("/imgUpload")
public Msg imgUpload(HttpServletRequest request, @RequestParam(required = true, value = "file") MultipartFile file,
@RequestParam(required = true, value = "days") String days) {
Msg msg = new Msg();
try{
if (null != file) {
msg = uploadServicel.uploadForLoc(request,file,Integer.valueOf(days),null);
}else{
msg.setCode("500");
}
}catch (Exception e){
e.printStackTrace();
msg.setCode("500");
}
return msg;
}
@PostMapping("/imgUploadForCopy")
public Msg imgUploadForCopy(@RequestParam(required = true, value = "data") String data, HttpServletRequest request) {
Msg msg = new Msg();
try{
JSONObject jsonObj = JSONObject.parseObject(data);
String imgstr = jsonObj.getString("imgstr");
Integer days = jsonObj.getInteger("days");
if (null != imgstr && !imgstr.isEmpty()) {
MultipartFile multipartFile = Base64ToMultipartFile.base64Convert(imgstr);
msg = uploadServicel.uploadForLoc(request, multipartFile, days, null);
}
}catch (Exception e){
e.printStackTrace();
msg.setCode("500");
}
return msg;
}
}
@@ -1,26 +1,13 @@
package cn.hellohao.controller; package cn.hellohao.controller;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.Msg;
import cn.hellohao.service.*; import cn.hellohao.service.impl.ClientService;
import cn.hellohao.service.impl.*; import org.apache.commons.lang3.StringUtils;
import cn.hellohao.utils.*;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
/** /**
* @author Hellohao * @author Hellohao
@@ -28,18 +15,30 @@ import java.util.*;
* @date 2019-07-18 17:22 * @date 2019-07-18 17:22
*/ */
@RestController @RestController
@RequestMapping("/api")
public class ClientController { public class ClientController {
@Autowired @Autowired private ClientService clientService;
private ClientService clientService;
@PostMapping(value = "/uploadbymail") @PostMapping(value = "/uploadbymail")
@ResponseBody @ResponseBody
public Msg uploadbymail(HttpServletRequest request, @RequestParam("file") MultipartFile file, String mail, String pass) { public Msg uploadbymail(
Msg resultBean = clientService.uploadImg(request, file, mail, pass); HttpServletRequest request,
@RequestParam(value = "file") MultipartFile file,
@RequestParam(value = "mail", defaultValue = "") String mail,
@RequestParam(value = "pass", defaultValue = "") String pass,
@RequestParam(value = "days", defaultValue = "0") String days) {
if (file == null
|| StringUtils.isBlank(mail)
|| StringUtils.isBlank(pass)) {
Msg msg = new Msg();
msg.setCode("400");
msg.setInfo("相关参数不能为空");
return msg;
}
Msg resultBean =
clientService.uploadImg(
request, file, mail, pass, Integer.valueOf(days.toString()));
return resultBean; return resultBean;
} }
} }
@@ -26,11 +26,10 @@ public class CodeController {
@Autowired @Autowired
private CodeService codeService; private CodeService codeService;
@RequestMapping(value = "/selectCodeList")
@RequestMapping(value = "/selectCodeList")//new
@ResponseBody @ResponseBody
public Map<String, Object> selectCodeList(@RequestParam(value = "data", defaultValue = "") String data) { public Msg selectCodeList(@RequestParam(value = "data", defaultValue = "") String data) {
Map<String, Object> map = new HashMap<String, Object>(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
Integer pageNum = jsonObj.getInteger("pageNum"); Integer pageNum = jsonObj.getInteger("pageNum");
Integer pageSize = jsonObj.getInteger("pageSize"); Integer pageSize = jsonObj.getInteger("pageSize");
@@ -39,19 +38,16 @@ public class CodeController {
try { try {
codes = codeService.selectCode(null); codes = codeService.selectCode(null);
PageInfo<Code> rolePageInfo = new PageInfo<>(codes); PageInfo<Code> rolePageInfo = new PageInfo<>(codes);
map.put("code", 200); msg.setData(rolePageInfo);
map.put("info", "");
map.put("count", rolePageInfo.getTotal());
map.put("data", rolePageInfo.getList());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
map.put("code", 500); msg.setCode("500");
map.put("info", "获取数据异常"); msg.setInfo("获取数据异常");
} }
return map; return msg;
} }
@RequestMapping("/deleteCodes")//new @RequestMapping("/deleteCodes")
@ResponseBody @ResponseBody
public Msg deletecodes(@RequestParam(value = "data", defaultValue = "") String data){ public Msg deletecodes(@RequestParam(value = "data", defaultValue = "") String data){
final Msg msg = new Msg(); final Msg msg = new Msg();
@@ -73,7 +69,7 @@ public class CodeController {
} }
@RequestMapping("/addCode")//new @RequestMapping("/addCode")
@ResponseBody @ResponseBody
public Msg addcode(@RequestParam(value = "data", defaultValue = "") String data){ public Msg addcode(@RequestParam(value = "data", defaultValue = "") String data){
final Msg msg = new Msg(); final Msg msg = new Msg();
@@ -3,16 +3,12 @@ package cn.hellohao.controller;
import cn.hellohao.exception.StorageSourceInitException; import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.utils.Print; import cn.hellohao.utils.Print;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import java.net.SocketException; import java.net.SocketException;
import java.util.Date;
import java.util.List;
/** /**
* @author Hellohao * @author Hellohao
@@ -24,7 +20,6 @@ import java.util.List;
public class ExceptionHandling { public class ExceptionHandling {
@ExceptionHandler @ExceptionHandler
//@ResponseBody
public ModelAndView test(StorageSourceInitException ssie){ public ModelAndView test(StorageSourceInitException ssie){
ModelAndView modelAndView = new ModelAndView("index"); ModelAndView modelAndView = new ModelAndView("index");
Print.Normal("异常拦截成功:"+ ssie.getMessage()); Print.Normal("异常拦截成功:"+ ssie.getMessage());
@@ -39,7 +34,6 @@ public class ExceptionHandling {
Print.Normal("存储源配置不正确,初始化失败"+ e.getMessage()); Print.Normal("存储源配置不正确,初始化失败"+ e.getMessage());
e.printStackTrace(); e.printStackTrace();
modelAndView.addObject("error",e.getMessage()); modelAndView.addObject("error",e.getMessage());
//返回错误信息,并显示给用户
return e.getMessage(); return e.getMessage();
} }
@ExceptionHandler @ExceptionHandler
@@ -48,7 +42,6 @@ public class ExceptionHandling {
Print.Normal("系统内部错误:"+ e.getMessage()); Print.Normal("系统内部错误:"+ e.getMessage());
e.printStackTrace(); e.printStackTrace();
modelAndView.addObject("error",e.getMessage()); modelAndView.addObject("error",e.getMessage());
//返回错误信息,并显示给用户
return e.getMessage(); return e.getMessage();
} }
@@ -57,11 +50,8 @@ public class ExceptionHandling {
ModelAndView modelAndView = new ModelAndView("/index"); ModelAndView modelAndView = new ModelAndView("/index");
Print.Normal("URL访问类型不正确:"+ e.getMessage()); Print.Normal("URL访问类型不正确:"+ e.getMessage());
//e.printStackTrace();
modelAndView.addObject("error","URL访问类型不正确。"); modelAndView.addObject("error","URL访问类型不正确。");
model.addAttribute("error","URL访问类型不正确。"); model.addAttribute("error","URL访问类型不正确。");
//返回错误信息,并显示给用户
//return e.getMessage();
return "exception"; return "exception";
} }
@@ -3,8 +3,6 @@ package cn.hellohao.controller;
import cn.hellohao.pojo.Group; import cn.hellohao.pojo.Group;
import cn.hellohao.pojo.Msg; import cn.hellohao.pojo.Msg;
import cn.hellohao.service.GroupService; import cn.hellohao.service.GroupService;
import cn.hellohao.service.KeysService;
import cn.hellohao.service.UserService;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
@@ -14,9 +12,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* @author Hellohao * @author Hellohao
@@ -28,27 +25,21 @@ import java.util.Map;
public class GroupController { public class GroupController {
@Autowired @Autowired
private GroupService groupService; private GroupService groupService;
@Autowired
private KeysService keysService;
@Autowired
private UserService userService;
@PostMapping("/getGrouplistForUsers")
@PostMapping("/getGrouplistForUsers") //new
@ResponseBody @ResponseBody
public Msg getGrouplistForUsers() { public Msg getGrouplistForUsers() {
Msg msg = new Msg(); Msg msg = new Msg();
//只获取用户组type为0的,只有是0的才是未分配用户组的,才能给指定用户设置
List<Group> groupList = groupService.grouplist(0); List<Group> groupList = groupService.grouplist(0);
msg.setData(groupList); msg.setData(groupList);
return msg; return msg;
} }
@PostMapping(value = "/getGroupList")//new @PostMapping(value = "/getGroupList")
@ResponseBody @ResponseBody
public Map<String, Object> getgrouplist(@RequestParam(value = "data", defaultValue = "") String data) { public Msg getgrouplist(@RequestParam(value = "data", defaultValue = "") String data) {
Map<String, Object> map = new HashMap<String, Object>(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
Integer pageNum = jsonObj.getInteger("pageNum"); Integer pageNum = jsonObj.getInteger("pageNum");
Integer pageSize = jsonObj.getInteger("pageSize"); Integer pageSize = jsonObj.getInteger("pageSize");
@@ -57,19 +48,16 @@ public class GroupController {
try { try {
group = groupService.grouplist(null); group = groupService.grouplist(null);
PageInfo<Group> rolePageInfo = new PageInfo<>(group); PageInfo<Group> rolePageInfo = new PageInfo<>(group);
map.put("code", 200); msg.setData(rolePageInfo);
map.put("info", "");
map.put("count", rolePageInfo.getTotal());
map.put("data", rolePageInfo.getList());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
map.put("code", 500); msg.setCode("500");
map.put("info", "获取数据异常"); msg.setInfo("获取数据异常");
} }
return map; return msg;
} }
@PostMapping(value = "/addGroup")//new @PostMapping(value = "/addGroup")
@ResponseBody @ResponseBody
public Msg addisgroup(@RequestParam(value = "data", defaultValue = "") String data) { public Msg addisgroup(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObject = JSONObject.parseObject(data); JSONObject jsonObject = JSONObject.parseObject(data);
@@ -82,7 +70,7 @@ public class GroupController {
return msg; return msg;
} }
@PostMapping("/updateGroup")//new @PostMapping("/updateGroup")
@ResponseBody @ResponseBody
public Msg updategroup(@RequestParam(value = "data", defaultValue = "") String data) { public Msg updategroup(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObject = JSONObject.parseObject(data); JSONObject jsonObject = JSONObject.parseObject(data);
@@ -101,7 +89,7 @@ public class GroupController {
return msg; return msg;
} }
@PostMapping(value = "/deleGroup")//new @PostMapping(value = "/deleGroup")
@ResponseBody @ResponseBody
public Msg delegroup(@RequestParam(value = "data", defaultValue = "") String data) { public Msg delegroup(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObject = JSONObject.parseObject(data); JSONObject jsonObject = JSONObject.parseObject(data);
@@ -3,104 +3,136 @@ package cn.hellohao.controller;
import cn.hellohao.auth.token.JWTUtil; import cn.hellohao.auth.token.JWTUtil;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.service.*; import cn.hellohao.service.*;
import cn.hellohao.service.impl.*; import cn.hellohao.service.impl.UploadServicel;
import cn.hellohao.utils.*; import cn.hellohao.service.impl.deleImages;
import cn.hellohao.utils.verifyCode.IVerifyCodeGen; import cn.hellohao.utils.GetIPS;
import cn.hellohao.utils.verifyCode.SimpleCharVerifyCodeGenImpl; import cn.hellohao.utils.MyVersion;
import cn.hellohao.utils.verifyCode.VerifyCode; import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import java.util.List;
import javax.servlet.http.HttpSession; import java.util.UUID;
import java.io.*;
@Controller @Controller
public class IndexController { public class IndexController {
@Autowired @Autowired private ImgService imgService;
private ImgService imgService; @Autowired private SysConfigService sysConfigService;
@Autowired @Autowired private ConfdataService confdataService;
private SysConfigService sysConfigService; @Autowired private UploadConfigService uploadConfigService;
@Autowired @Autowired private UploadServicel uploadServicel;
IRedisService iRedisService; @Autowired private deleImages deleimages;
@Autowired @Autowired private IRedisService iRedisService;
private ConfigService configService; @Autowired private AppClientService appClientService;
@Autowired
private UploadConfigService uploadConfigService;
@Autowired
private UploadServicel uploadServicel;
@Autowired
private NOSImageupload nosImageupload;
@Autowired
private OSSImageupload ossImageupload;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private KODOImageupload kodoImageupload;
@Autowired
private USSImageupload ussImageupload;
@Autowired
private UFileImageupload uFileImageupload;
@Autowired
private FTPImageupload ftpImageupload;
@Autowired
AlbumServiceImpl albumService;
@Autowired
private KeysService keysService;
@Autowired
private ImgTempService imgTempService;
@Autowired
private ImgAndAlbumService imgAndAlbumService;
@RequestMapping(value = "/")
public String Welcome(Model model, HttpServletRequest httpServletRequest) {
model.addAttribute("name", "服务端程序(开源版)");
model.addAttribute("version", "20230320");
model.addAttribute("ip", GetIPS.getIpAddr(httpServletRequest));
model.addAttribute("links", "https://github.com/Hello-hao/tbed");
return "welcome";
}
@RequestMapping(value = "/webInfo") @RequestMapping(value = "/webInfo")
@ResponseBody @ResponseBody
public Msg webInfo() { public Msg webInfo() {
final Msg msg = new Msg(); Msg msg = new Msg();
Config config = configService.getSourceype(); final Confdata confdata = confdataService.selectConfdata("config");
JSONObject cd = JSONObject.parseObject(confdata.getJsondata());
UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
SysConfig sysConfig = sysConfigService.getstate(); SysConfig sysConfig = sysConfigService.getstate();
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("webname",config.getWebname()); AppClient appClient = appClientService.getAppClientData("app");
jsonObject.put("websubtitle",config.getWebsubtitle()); jsonObject.put("webname", cd.getString("webname"));
jsonObject.put("keywords",config.getWebkeywords()); jsonObject.put("websubtitle", cd.getString("websubtitle"));
jsonObject.put("description",config.getWebms()); jsonObject.put("keywords", cd.getString("keywords"));
jsonObject.put("explain",config.getExplain()); jsonObject.put("description", cd.getString("description"));
jsonObject.put("favicon",config.getWebfavicons()); jsonObject.put("explain", cd.getString("explain"));
jsonObject.put("baidu",config.getBaidu()); jsonObject.put("baidu", cd.getString("baidu"));
jsonObject.put("links",config.getLinks()); jsonObject.put("links", cd.getString("links"));
jsonObject.put("aboutinfo",config.getAboutinfo()); jsonObject.put("aboutinfo", cd.getString("aboutinfo"));
jsonObject.put("logo",config.getLogo()); jsonObject.put("logo", cd.getString("logo"));
jsonObject.put("api",updateConfig.getApi()); jsonObject.put("webfavicons", cd.getString("webfavicons"));
jsonObject.put("register",sysConfig.getRegister()); jsonObject.put("api", updateConfig.getApi());
jsonObject.put("register", sysConfig.getRegister());
jsonObject.put("isuse", appClient.getIsuse());
jsonObject.put("clientname", appClient.getAppname());
jsonObject.put("clientlogo", appClient.getApplogo());
jsonObject.put("appupdate", appClient.getAppupdate());
msg.setData(jsonObject); msg.setData(jsonObject);
return msg; return msg;
} }
@PostMapping(value = {"/upload", "/client/upload"})
@PostMapping(value = "/upload")//upimg new
@ResponseBody @ResponseBody
public Msg upimg(HttpServletRequest request,HttpSession httpSession public Msg upimg(
, @RequestParam(value = "file", required = false) MultipartFile multipartFile,Integer day, HttpServletRequest request,
@RequestParam(value = "classifications", defaultValue = "" ) String classifications) { @RequestParam(value = "file", required = false) MultipartFile multipartFile,
final JSONArray jsonArray = new JSONArray(); Integer day) {
if(!classifications.equals("")){ return uploadServicel.uploadForLoc(request, multipartFile, day, null);
String[] calssif = classifications.split(",");
for (int i = 0; i < calssif.length; i++) {
jsonArray.add(calssif[i]);
}
}
return uploadServicel.uploadForLoc(request,multipartFile,day,null,jsonArray);
} }
@RequestMapping(value = "/getUploadInfo")//new @PostMapping(value = {"/uploadForUrl", "/client/uploadForUrl"})
@ResponseBody
public Msg upurlimg(
HttpServletRequest request, @RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObj = JSONObject.parseObject(data);
Integer setday = jsonObj.getInteger("day");
String imgUrl = jsonObj.getString("imgUrl");
String[] URLArr = imgUrl.split("\n");
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
int syscounts = 0;
if (null == user) {
syscounts = updateConfig.getImgcounttourists();
} else {
syscounts = updateConfig.getImgcountuser();
}
Msg retMsg = new Msg();
JSONObject jsonObject = new JSONObject();
JSONArray retArray = new JSONArray();
int errcounts = 0;
int excess = 0;
for (int i = 0; i < URLArr.length; i++) {
int temp = i + 1;
if (syscounts >= temp) {
Msg msg = uploadServicel.uploadForLoc(request, null, setday, URLArr[i]);
if (!msg.getCode().equals("200")) {
errcounts++;
} else {
retArray.add(msg);
}
} else {
excess++;
}
}
jsonObject.put("counts", URLArr.length);
jsonObject.put("errcounts", errcounts);
jsonObject.put("excess", excess);
jsonObject.put("urls", retArray);
retMsg.setData(jsonObject);
return retMsg;
}
@RequestMapping(value = "/getUploadInfo")
@ResponseBody @ResponseBody
public Msg getUploadInfo() { public Msg getUploadInfo() {
Msg msg = new Msg(); Msg msg = new Msg();
@@ -109,42 +141,45 @@ public class IndexController {
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
try { try {
UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
jsonObject.put("suffix",updateConfig.getSuffix().split(",")); jsonObject.put("suffix", updateConfig.getSuffix().split(","));
if(null==user){ if (null == user) {
jsonObject.put("filesize",Integer.valueOf(updateConfig.getFilesizetourists())/1024); jsonObject.put("filesize", Integer.valueOf(updateConfig.getFilesizetourists()) / 1024);
jsonObject.put("imgcount",updateConfig.getImgcounttourists()); jsonObject.put("imgcount", updateConfig.getImgcounttourists());
jsonObject.put("uploadSwitch",updateConfig.getIsupdate()); jsonObject.put("uploadSwitch", updateConfig.getIsupdate());
jsonObject.put("uploadInfo","您登陆后才能使用此功能哦"); jsonObject.put("uploadInfo", "您登陆后才能使用此功能哦");
}else{ } else {
jsonObject.put("filesize",Integer.valueOf(updateConfig.getFilesizeuser())/1024); jsonObject.put("filesize", Integer.valueOf(updateConfig.getFilesizeuser()) / 1024);
jsonObject.put("imgcount",updateConfig.getImgcountuser()); jsonObject.put("imgcount", updateConfig.getImgcountuser());
jsonObject.put("uploadSwitch", updateConfig.getUserclose());
jsonObject.put("uploadInfo", "系统暂时关闭了用户上传功能");
} }
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
msg.setData(jsonObject); msg.setData(jsonObject);
return msg; return msg;
} }
@RequestMapping("/checkStatus") @RequestMapping("/checkStatus")
@ResponseBody @ResponseBody
public Msg checkStatus(HttpServletRequest request) { public Msg checkStatus(HttpServletRequest request) {
Msg msg = new Msg(); Msg msg = new Msg();
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
if(token != null) { if (token != null) {
JSONObject tokenJson = JWTUtil.checkToken(token); JSONObject tokenJson = JWTUtil.checkToken(token);
if(tokenJson.getBoolean("check")){ if (tokenJson.getBoolean("check")) {
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(tokenJson.getString("email"),tokenJson.getString("password")); UsernamePasswordToken tokenOBJ =
new UsernamePasswordToken(
tokenJson.getString("email"), tokenJson.getString("password"));
tokenOBJ.setRememberMe(true); tokenOBJ.setRememberMe(true);
try { try {
subject.login(tokenOBJ); subject.login(tokenOBJ);
SecurityUtils.getSubject().getSession().setTimeout(3600000); SecurityUtils.getSubject().getSession().setTimeout(3600000);
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
final JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("RoleLevel",u.getLevel()==2?"admin":"user"); jsonObject.put("RoleLevel", u.getLevel() == 2 ? "admin" : "user");
jsonObject.put("userName",u.getUsername()); jsonObject.put("userName", u.getUsername());
msg.setCode("200"); msg.setCode("200");
msg.setData(jsonObject); msg.setData(jsonObject);
} catch (Exception e) { } catch (Exception e) {
@@ -153,164 +188,172 @@ public class IndexController {
System.err.println("登录失效,请重新登录"); System.err.println("登录失效,请重新登录");
e.printStackTrace(); e.printStackTrace();
} }
}else{ } else {
msg.setCode("40041"); msg.setCode("40041");
msg.setInfo("登录失效,请重新登录"); msg.setInfo("登录失效,请重新登录");
} }
}else{ } else {
msg.setCode("40040"); msg.setCode("40040");
msg.setInfo("当前未登录,请先登录"); msg.setInfo("当前未登录,请先登录");
} }
return msg; return msg;
} }
@PostMapping("/verifyCode")
@ResponseBody
@GetMapping("/verifyCode") public Msg verifyCode() {
public void verifyCode(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) { Msg msg = new Msg();
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
try { try {
//登录页面验证码 ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(90, 35, 2, 2);
VerifyCode verifyCode = iVerifyCodeGen.generate(80, 38); captcha.setGenerator(new MathGenerator(1));
String code = verifyCode.getCode(); String code = getVerifyCodeOperator(captcha.getCode());
String userIP = GetIPS.getIpAddr(request); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
iRedisService.setValue(userIP+"_hellohao_verifyCode",code); iRedisService.setValue("verifyCode_" + uid, code);
response.setHeader("Pragma", "no-cache"); JSONObject jsonObject = new JSONObject();
response.setHeader("Cache-Control", "no-cache"); jsonObject.put("codeKey", uid);
response.setDateHeader("Expires", 0); jsonObject.put("codeImg", captcha.getImageBase64());
response.setContentType("image/jpeg"); msg.setData(jsonObject);
response.getOutputStream().write(verifyCode.getImgBytes()); return msg;
response.getOutputStream().flush(); } catch (Exception e) {
} catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
msg.setCode("500");
return msg;
} }
} }
@GetMapping("/verifyCodeForRegister") @PostMapping("/verifyCodeForRegister")
public void verifyCodeForRegister(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) { @ResponseBody
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl(); public Msg verifyCodeForRegister() {
Msg msg = new Msg();
try { try {
VerifyCode verifyCode = iVerifyCodeGen.generate(80, 38); ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(90, 35, 2, 2);
String code = verifyCode.getCode(); captcha.setGenerator(new MathGenerator(1));
String userIP = GetIPS.getIpAddr(request); String code = getVerifyCodeOperator(captcha.getCode());
iRedisService.setValue(userIP+"_hellohao_verifyCodeForRegister",code); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
response.setHeader("Pragma", "no-cache"); iRedisService.setValue("verifyCodeForRegister_" + uid, code);
response.setHeader("Cache-Control", "no-cache"); JSONObject jsonObject = new JSONObject();
response.setDateHeader("Expires", 0); jsonObject.put("codeKey", uid);
response.setContentType("image/jpeg"); jsonObject.put("codeImg", captcha.getImageBase64());
response.getOutputStream().write(verifyCode.getImgBytes()); msg.setData(jsonObject);
response.getOutputStream().flush(); return msg;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setCode("500");
return msg;
} }
} }
@GetMapping("/verifyCodeForRetrieve") @PostMapping("/verifyCodeForRetrieve")
public void verifyCodeForRetrieve(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) { @ResponseBody
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl(); public Msg verifyCodeForRetrieve() {
Msg msg = new Msg();
try { try {
VerifyCode verifyCode = iVerifyCodeGen.generate(80, 38); ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(90, 35, 2, 2);
String code = verifyCode.getCode(); captcha.setGenerator(new MathGenerator(1));
System.out.println("verifyCodeForRetrieve-zhaoHui httpSession ID==="+httpSession.getId()); String code = getVerifyCodeOperator(captcha.getCode());
String userIP = GetIPS.getIpAddr(request); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
iRedisService.setValue(userIP+"_hellohao_verifyCodeForEmailRetrieve",code); iRedisService.setValue("verifyCodeForRetrieve_" + uid, code);
response.setHeader("Pragma", "no-cache"); JSONObject jsonObject = new JSONObject();
response.setHeader("Cache-Control", "no-cache"); jsonObject.put("codeKey", uid);
response.setDateHeader("Expires", 0); jsonObject.put("codeImg", captcha.getImageBase64());
response.setContentType("image/jpeg"); msg.setData(jsonObject);
response.getOutputStream().write(verifyCode.getImgBytes()); return msg;
response.getOutputStream().flush(); } catch (Exception e) {
} catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
msg.setCode("500");
return msg;
} }
} }
//删除图像 public static String getVerifyCodeOperator(String str) {
@PostMapping("/deleImagesByUid") //new int a = Integer.valueOf(str.substring(0, 1));
String yxf = str.substring(1, 2);
int b = Integer.valueOf(str.substring(2, 3));
switch (yxf) {
case "*":
return Integer.toString(a * b);
case "+":
return Integer.toString(a + b);
case ",":
default:
return Integer.toString(82);
case "-":
return Integer.toString(a - b);
}
}
@PostMapping({"/deleImagesByUid", "/client/deleImagesByUid"})
@ResponseBody @ResponseBody
public Msg deleImagesByUid(@RequestParam(value = "data", defaultValue = "") String data) { public Msg deleImagesByUid(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
String imguid = jsonObj.getString("imguid"); String imguid = jsonObj.getString("imguid");
Images image = imgService.selectImgUrlByImgUID(imguid); Images image = imgService.selectImgUrlByImgUID(imguid);
if (null == image) {
msg.setInfo("图像已不存在,删除成功");
return msg;
}
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
if(null!=user){ if (null != user) {
if(user.getId()!=image.getUserid()){ if (!user.getId().equals(image.getUserid())) {
msg.setInfo("删除失败,该图片不允许你执行操作"); msg.setInfo("删除失败,该图片不允许你执行操作");
msg.setCode("100403"); msg.setCode("100403");
return msg; return msg;
} }
} }
Integer keyid = image.getSource(); msg = deleimages.dele(null, image.getId());
String imgname = image.getImgname(); List<Long> Delids = (List<Long>) msg.getData();
Keys key = keysService.selectKeys(keyid); if (!Delids.contains(image.getId())) {
//删除图片
boolean isDele = false;
if (key.getStorageType() == 1) {
isDele = nosImageupload.delNOS(key.getId(), imgname);
} else if (key.getStorageType() == 2) {
isDele = ossImageupload.delOSS(key.getId(), imgname);
} else if (key.getStorageType() == 3) {
isDele = ussImageupload.delUSS(key.getId(), imgname);
} else if (key.getStorageType() == 4) {
isDele = kodoImageupload.delKODO(key.getId(), imgname);
} else if (key.getStorageType() == 5) {
isDele = LocUpdateImg.deleteLOCImg(imgname);
}else if (key.getStorageType() == 6) {
isDele = cosImageupload.delCOS(key.getId(), imgname);
}else if (key.getStorageType() == 7) {
isDele = ftpImageupload.delFTP(key.getId(), imgname);
}else if (key.getStorageType() == 8) {
isDele = uFileImageupload.delUFile(key.getId(), imgname);
}else {
System.err.println("未获取到对象存储参数,删除失败。");
}
//删除库
if(isDele){
try {
imgAndAlbumService.deleteImgAndAlbum(imgname);
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
} catch (Exception e) {
e.printStackTrace();
msg.setInfo("图片记录时发生错误");
msg.setCode("500");
return msg;
}
msg.setInfo("删除成功");
}else{
imgAndAlbumService.deleteImgAndAlbum(imgname);
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
msg.setInfo("图片记录已删除,但是图片源删除失败");
msg.setCode("500"); msg.setCode("500");
msg.setInfo("图像删除失败");
} else {
msg.setCode("200");
msg.setInfo("图像已成功删除");
} }
System.out.println("返回的值:"+msg.toString());
return msg; return msg;
} }
@PostMapping("/getClientVersion")
@ResponseBody
public Msg getClientVersion(@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg();
msg.setCode("000");
try {
JSONObject jsonObj = JSONObject.parseObject(data);
String appv = jsonObj.getString("version");
AppClient app = appClientService.getAppClientData("app");
if (!StringUtils.isBlank(app.getAppupdate())) {
String version = app.getAppupdate().replaceAll("\\.", "");
if (MyVersion.compareVersion(app.getAppupdate(), appv) == 1) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("winpackurl", app.getWinpackurl());
jsonObject.put("macpackurl", app.getMacpackurl());
msg.setCode("200");
msg.setData(jsonObject);
}
}
} catch (Exception e) {
msg.setCode("000");
}
return msg;
}
//没有权限
@RequestMapping("/authError") @RequestMapping("/authError")
@ResponseBody @ResponseBody
public Msg authError(HttpServletRequest request){ public Msg authError(HttpServletRequest request) {
Msg msg = new Msg(); Msg msg = new Msg();
msg.setCode("4031"); msg.setCode("4031");
msg.setInfo("You don't have authority"); msg.setInfo("You don't have authority");
return msg; return msg;
} }
//认证失败
@RequestMapping("/jurisError") @RequestMapping("/jurisError")
@ResponseBody @ResponseBody
public Msg jurisError(HttpServletRequest request){ public Msg jurisError(HttpServletRequest request) {
Msg msg = new Msg(); Msg msg = new Msg();
msg.setCode("4031"); msg.setCode("4031");
msg.setInfo("Authentication request failed"); msg.setInfo("Authentication request failed");
return msg; return msg;
} }
} }
@@ -1,19 +1,16 @@
package cn.hellohao.controller; package cn.hellohao.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.hellohao.auth.filter.SubjectFilter; import cn.hellohao.auth.filter.SubjectFilter;
import cn.hellohao.auth.token.JWTUtil; import cn.hellohao.auth.token.JWTUtil;
import cn.hellohao.config.SysName; import cn.hellohao.config.SysName;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.service.*; import cn.hellohao.service.*;
import cn.hellohao.utils.*; import cn.hellohao.utils.Base64Encryption;
import cn.hellohao.utils.NewSendEmail;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.SetText;
import cn.hutool.core.util.HexUtil; import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UnknownAccountException;
@@ -23,7 +20,13 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Controller @Controller
@@ -34,34 +37,33 @@ public class UserController {
@Autowired @Autowired
private EmailConfigService emailConfigService; private EmailConfigService emailConfigService;
@Autowired @Autowired
private ConfigService configService; private ConfdataService confdataService;
@Autowired @Autowired
private UploadConfigService uploadConfigService; private UploadConfigService uploadConfigService;
@Autowired @Autowired
private SysConfigService sysConfigService; private SysConfigService sysConfigService;
@Autowired @Autowired
private UserGroupService userGroupService;
@Autowired
IRedisService iRedisService; IRedisService iRedisService;
@PostMapping("/register") @PostMapping("/register")
@ResponseBody @ResponseBody
public Msg Register(HttpServletRequest request,@RequestParam(value = "data", defaultValue = "") String data) {//Validated public Msg Register(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
String username = jsonObj.getString("username"); String username = jsonObj.getString("username");
String email = jsonObj.getString("email"); String email = jsonObj.getString("email");
String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes()); String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes());
String userIP = GetIPS.getIpAddr(request);
String verifyCodeForRegister = jsonObj.getString("verifyCode"); String verifyCodeForRegister = jsonObj.getString("verifyCode");
Object redis_verifyCodeForRegister = iRedisService.getValue(userIP+"_hellohao_verifyCodeForRegister"); Object redis_verifyCodeForRegister = iRedisService.getValue("verifyCodeForRegister_"+httpServletRequest.getHeader("verifyCodeForRegister"));
if(!SetText.checkEmail(email)){ if(!SetText.checkEmail(email)){
//邮箱格式不正确
msg.setCode("110403"); msg.setCode("110403");
msg.setInfo("邮箱格式不正确"); msg.setInfo("邮箱格式不正确");
return msg; return msg;
} }
String regex = "^\\w+$"; String regex = "^\\w+$";
if(username.length()>20 || !username.matches (regex)){ if(username.length()>20 || !username.matches (regex)){
//用户名格式不正确
msg.setCode("110403"); msg.setCode("110403");
msg.setInfo("用户名不得超过20位字符"); msg.setInfo("用户名不得超过20位字符");
return msg; return msg;
@@ -108,14 +110,16 @@ public class UserController {
user.setEmail(email); user.setEmail(email);
user.setUsername(username); user.setUsername(username);
user.setPassword(password); user.setPassword(password);
Config config = configService.getSourceype(); user.setToken(UUID.randomUUID().toString().replace("-", ""));
final Confdata confdata = confdataService.selectConfdata("config");
JSONObject jsonObject = JSONObject.parseObject(confdata.getJsondata());
Integer type = 0; Integer type = 0;
if(emailConfig.getUsing()==1){ if(emailConfig.getUsing()==1){
user.setIsok(0); user.setIsok(0);
//注册完发激活链接 //注册完发激活链接
Thread thread = new Thread() { Thread thread = new Thread() {
public void run() { public void run() {
Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), uid, user.getEmail(),config); Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), uid, user.getEmail(),jsonObject);
} }
}; };
thread.start(); thread.start();
@@ -135,14 +139,25 @@ public class UserController {
@PostMapping("/login")//new @PostMapping("/login")//new
@ResponseBody @ResponseBody
public Msg login(HttpServletRequest request,@RequestParam(value = "data", defaultValue = "") String data) { public Msg login(HttpServletRequest httpServletRequest,@RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
String email = jsonObj.getString("email"); String email = jsonObj.getString("email");
String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes()); String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes());
String verifyCode = jsonObj.getString("verifyCode"); String verifyCode = jsonObj.getString("verifyCode");
String userIP = GetIPS.getIpAddr(request); if(null == email || null == password || null == verifyCode){
Object redis_VerifyCode = iRedisService.getValue(userIP+"_hellohao_verifyCode"); msg.setCode("5000");
msg.setInfo("登录信息不正确");
return msg;
}
if(email.replace(" ","").equals("") || password.replace(" ","").equals("")
|| verifyCode.replace(" ","").equals("")){
msg.setCode("5000");
msg.setInfo("登录信息不正确");
return msg;
}
Object redis_VerifyCode = iRedisService.getValue("verifyCode_"+httpServletRequest.getHeader("verifyCode"));
if(null==redis_VerifyCode){ if(null==redis_VerifyCode){
msg.setCode("4035"); msg.setCode("4035");
msg.setInfo("验证码已失效,请重新弄获取。"); msg.setInfo("验证码已失效,请重新弄获取。");
@@ -158,7 +173,7 @@ public class UserController {
tokenOBJ.setRememberMe(true); tokenOBJ.setRememberMe(true);
try { try {
subject.login(tokenOBJ); subject.login(tokenOBJ);
SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时 SecurityUtils.getSubject().getSession().setTimeout(3600000);
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
User user = (User) SecurityUtils.getSubject().getPrincipal(); User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user.getIsok()==0){ if(user.getIsok()==0){
@@ -202,17 +217,14 @@ public class UserController {
} }
}else{ }else{
msg.setCode("40034"); msg.setCode("40034");
msg.setInfo("验证码不正确");//失效也要处理。 msg.setInfo("验证码不正确");
} }
return msg; return msg;
} }
//邮箱激活
@RequestMapping(value = "/activation", method = RequestMethod.GET) @RequestMapping(value = "/activation", method = RequestMethod.GET)
public String activation(Model model, HttpServletRequest request, HttpSession session, String activation, String username) { public String activation(Model model, HttpServletRequest request, HttpSession session, String activation, String username) {
Config config = configService.getSourceype();
Integer ret = 0; Integer ret = 0;
User u2 = new User(); User u2 = new User();
u2.setUid(activation); u2.setUid(activation);
@@ -232,7 +244,6 @@ public class UserController {
} }
} }
//退出
@PostMapping(value = "/logout")//new @PostMapping(value = "/logout")//new
@ResponseBody @ResponseBody
public Msg exit(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { public Msg exit(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
@@ -244,18 +255,15 @@ public class UserController {
return msg; return msg;
} }
//retrievepass @PostMapping("/retrievePass")
@PostMapping("/retrievePass") //new
@ResponseBody @ResponseBody
public Msg retrievePass(HttpServletRequest request, @RequestParam(value = "data", defaultValue = "") String data) { public Msg retrievePass(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) {
Msg msg = new Msg(); Msg msg = new Msg();
try { try {
JSONObject jsonObj = JSONObject.parseObject(data); JSONObject jsonObj = JSONObject.parseObject(data);
String email = jsonObj.getString("email"); String email = jsonObj.getString("email");
String retrieveCode = jsonObj.getString("retrieveCode"); String retrieveCode = jsonObj.getString("retrieveCode");
String userIP = GetIPS.getIpAddr(request); Object redis_verifyCodeForEmailRetrieve =iRedisService.getValue("verifyCodeForRetrieve_"+httpServletRequest.getHeader("verifyCodeForRetrieve"));
Object redis_verifyCodeForEmailRetrieve = iRedisService.getValue(userIP+"_hellohao_verifyCodeForEmailRetrieve");
EmailConfig emailConfig = emailConfigService.getemail(); EmailConfig emailConfig = emailConfigService.getemail();
if(null==redis_verifyCodeForEmailRetrieve){ if(null==redis_verifyCodeForEmailRetrieve){
msg.setCode("4035"); msg.setCode("4035");
@@ -271,7 +279,6 @@ public class UserController {
msg.setInfo("验证码不正确"); msg.setInfo("验证码不正确");
return msg; return msg;
} }
Integer ret = userService.countmail(email); Integer ret = userService.countmail(email);
if(ret>0){ if(ret>0){
if(emailConfig.getUsing()==1){ if(emailConfig.getUsing()==1){
@@ -283,10 +290,11 @@ public class UserController {
msg.setInfo("当前用户已被冻结,禁止操作"); msg.setInfo("当前用户已被冻结,禁止操作");
return msg; return msg;
} }
Config config = configService.getSourceype(); final Confdata confdata = confdataService.selectConfdata("config");
JSONObject jsonObject = JSONObject.parseObject(confdata.getJsondata());
Thread thread = new Thread() { Thread thread = new Thread() {
public void run() { public void run() {
Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),config);//SendEmail.sendEmailT(message, user.getUsername(), user.getUid(), user.getEmail(),emailConfig,config); Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),jsonObject);
} }
}; };
thread.start(); thread.start();
@@ -307,8 +315,7 @@ public class UserController {
return msg; return msg;
} }
//邮箱激活 @RequestMapping(value = "/retrieve", method = RequestMethod.GET)
@RequestMapping(value = "/retrieve", method = RequestMethod.GET) //new
public String retrieve(Model model, String activation,String cip) { public String retrieve(Model model, String activation,String cip) {
Integer ret = 0; Integer ret = 0;
try { try {
@@ -341,10 +348,5 @@ public class UserController {
} }
private Integer number1;
private Integer istmp1;
private Integer number2;
private Integer istmp2;
} }
@@ -23,4 +23,6 @@ public interface AlbumMapper {
List<Album> selectAlbumURLList(Album album); List<Album> selectAlbumURLList(Album album);
Integer selectAlbumCount(@Param("userid") Integer userid); Integer selectAlbumCount(@Param("userid") Integer userid);
Integer updateAlbum(Album album);
} }
@@ -0,0 +1,19 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.AppClient;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @author Hellohao
* @version 1.0
* @date 2022-06-10 18:33
*/
@Mapper
public interface AppClientMapper {
AppClient getAppClientData(@Param("id") String id);
Integer editAppClientData(AppClient appClient);
}
@@ -0,0 +1,11 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Confdata;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ConfdataMapper {
Confdata selectConfdata(@Param("key") String key);
Integer updateConfdata(Confdata confdata);
}
@@ -1,11 +0,0 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Config;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
@Mapper
public interface ConfigMapper {
Config getSourceype();
Integer setSourceype(Config config);
}
+10 -9
View File
@@ -1,30 +1,33 @@
package cn.hellohao.dao; package cn.hellohao.dao;
import java.util.List; import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User; import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import cn.hellohao.pojo.Images; import java.util.List;
@Mapper @Mapper
public interface ImgMapper { public interface ImgMapper {
List<Images> selectimg(Images images); List<Images> selectimg(Images images);
Integer insertImgData(Images images);
Integer countimg(@Param("userid") Integer userid); Integer countimg(@Param("userid") Integer userid);
Integer deleimg(@Param("id") Integer id); Integer deleimg(@Param("id") Long id);
Images selectByPrimaryKey(@Param("id") Integer id); Integer deleimgForImgUid(@Param("imguid") String imguid);
Images selectByPrimaryKey(@Param("id") Long id);
Integer counts(@Param("userid") Integer userid); Integer counts(@Param("userid") Integer userid);
Integer setImg(Images images); Integer setImg(Images images);
Integer deleimgname(@Param("imgname") String imgname); Integer deleimgname(@Param("imgname") String imgname);
Integer deleall(@Param("id") Integer id); Integer deleall(@Param("id") Long id);
List<Images> gettimeimg(@Param("time") String time); List<Images> gettimeimg(@Param("time") String time);
@@ -34,14 +37,12 @@ public interface ImgMapper {
Integer md5Count(Images images); Integer md5Count(Images images);
Images selectImgUrlByMD5(@Param("md5key") String md5key); List<Images> selectImgUrlByMD5(@Param("md5key") String md5key);
List<Images> RecentlyUploaded(@Param("userid") Integer userid); List<Images> RecentlyUploaded(@Param("userid") Integer userid);
List<User> RecentlyUser(); List<User> RecentlyUser();
Integer addGreat(@Param("id") Integer id);
List<String> getyyyy(@Param("userid") Integer userid); List<String> getyyyy(@Param("userid") Integer userid);
List<Images> countByM(Images images); List<Images> countByM(Images images);
@@ -1,9 +0,0 @@
package cn.hellohao.dao;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface NoticeMapper {
String getNotice();
}
+2 -26
View File
@@ -1,54 +1,30 @@
package cn.hellohao.dao; package cn.hellohao.dao;
import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User;
import java.util.List; import java.util.List;
@Mapper @Mapper
public interface UserMapper { public interface UserMapper {
//注册
Integer register(User user); Integer register(User user);
//登录
Integer login(@Param("email") String email, @Param("password") String password,@Param("uid") String uid); Integer login(@Param("email") String email, @Param("password") String password,@Param("uid") String uid);
//获取用户信息
User getUsers(User user); User getUsers(User user);
User loginByToken (@Param("token") String token);
//插入图片
Integer insertimg(Images img);
//修改资料
Integer change(User user); Integer change(User user);
Integer changeUser(User user); Integer changeUser(User user);
//检查用户名是否重复
Integer checkUsername(@Param("username") String username); Integer checkUsername(@Param("username") String username);
Integer getUserTotal(); Integer getUserTotal();
List<User> getuserlist(String username); List<User> getuserlist(String username);
//刪除用戶
Integer deleuser(@Param("id") Integer id); Integer deleuser(@Param("id") Integer id);
//查询用户名或者邮箱是否存在
Integer countusername(@Param("username") String username); Integer countusername(@Param("username") String username);
Integer countmail(@Param("email") String email); Integer countmail(@Param("email") String email);
Integer uiduser(@Param("uid") String uid); Integer uiduser(@Param("uid") String uid);
User getUsersMail(@Param("uid") String uid); User getUsersMail(@Param("uid") String uid);
Integer setisok (User user); Integer setisok (User user);
Integer setmemory(User user); Integer setmemory(User user);
User getUsersid(@Param("id") Integer id); User getUsersid(@Param("id") Integer id);
List<User> getuserlistforgroupid(@Param("groupid") Integer groupid); List<User> getuserlistforgroupid(@Param("groupid") Integer groupid);
} }
@@ -0,0 +1,81 @@
package cn.hellohao.pojo;
public class AppClient {
private String id;
private String isuse;
private String winpackurl;
private String macpackurl;
private String appname;
private String applogo;
private String appupdate;
public AppClient(){}
public AppClient(String id, String isuse, String winpackurl, String macpackurl, String appname, String applogo, String appupdate) {
this.id = id;
this.isuse = isuse;
this.winpackurl = winpackurl;
this.macpackurl = macpackurl;
this.appname = appname;
this.applogo = applogo;
this.appupdate = appupdate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIsuse() {
return isuse;
}
public void setIsuse(String isuse) {
this.isuse = isuse;
}
public String getWinpackurl() {
return winpackurl;
}
public void setWinpackurl(String winpackurl) {
this.winpackurl = winpackurl;
}
public String getMacpackurl() {
return macpackurl;
}
public void setMacpackurl(String macpackurl) {
this.macpackurl = macpackurl;
}
public String getAppname() {
return appname;
}
public void setAppname(String appname) {
this.appname = appname;
}
public String getApplogo() {
return applogo;
}
public void setApplogo(String applogo) {
this.applogo = applogo;
}
public String getAppupdate() {
return appupdate;
}
public void setAppupdate(String isupdate) {
this.appupdate = isupdate;
}
}
@@ -0,0 +1,16 @@
package cn.hellohao.pojo;
import lombok.Data;
/**
* @author Hellohao
* @version 1.0
* @date 2023/3/2 10:21
*/
@Data
public class Confdata {
private String key;
private String jsondata;
}
+3 -196
View File
@@ -1,5 +1,8 @@
package cn.hellohao.pojo; package cn.hellohao.pojo;
import lombok.Data;
@Data
public class Config { public class Config {
private Integer id; private Integer id;
private Integer sourcekey; private Integer sourcekey;
@@ -23,201 +26,5 @@ public class Config {
private String logo; private String logo;
private String aboutinfo; private String aboutinfo;
public Config() {
}
public Config(Integer id, Integer sourcekey, Integer emails, String webname, String explain, String video, Integer backtype,
String links, String notice, String baidu, String domain, String background1, String background2, String sett,
String webms, String webkeywords, String webfavicons, Integer theme,String websubtitle,String logo,String aboutinfo) {
this.id = id;
this.sourcekey = sourcekey;
this.emails = emails;
this.webname = webname;
this.explain = explain;
this.video = video;
this.backtype = backtype;
this.links = links;
this.notice = notice;
this.baidu = baidu;
this.domain = domain;
this.background1 = background1;
this.background2 = background2;
this.sett = sett;
this.webms = webms;
this.webkeywords = webkeywords;
this.webfavicons = webfavicons;
this.theme = theme;
this.websubtitle = websubtitle;
this.logo = logo;
this.aboutinfo = aboutinfo;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getSourcekey() {
return sourcekey;
}
public void setSourcekey(Integer sourcekey) {
this.sourcekey = sourcekey;
}
public Integer getEmails() {
return emails;
}
public void setEmails(Integer emails) {
this.emails = emails;
}
public String getWebname() {
return webname;
}
public void setWebname(String webname) {
this.webname = webname;
}
public String getExplain() {
return explain;
}
public void setExplain(String explain) {
this.explain = explain;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public Integer getBacktype() {
return backtype;
}
public void setBacktype(Integer backtype) {
this.backtype = backtype;
}
public String getLinks() {
return links;
}
public void setLinks(String links) {
this.links = links;
}
public String getNotice() {
return notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
public String getBaidu() {
return baidu;
}
public void setBaidu(String baidu) {
this.baidu = baidu;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getBackground1() {
return background1;
}
public void setBackground1(String background1) {
this.background1 = background1;
}
public String getBackground2() {
return background2;
}
public void setBackground2(String background2) {
this.background2 = background2;
}
public String getSett() {
return sett;
}
public void setSett(String sett) {
this.sett = sett;
}
public String getWebms() {
return webms;
}
public void setWebms(String webms) {
this.webms = webms;
}
public String getWebkeywords() {
return webkeywords;
}
public void setWebkeywords(String webkeywords) {
this.webkeywords = webkeywords;
}
public String getWebfavicons() {
return webfavicons;
}
public void setWebfavicons(String webfavicons) {
this.webfavicons = webfavicons;
}
public Integer getTheme() {
return theme;
}
public void setTheme(Integer theme) {
this.theme = theme;
}
public String getWebsubtitle() {
return websubtitle;
}
public void setWebsubtitle(String websubtitle) {
this.websubtitle = websubtitle;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getAboutinfo() {
return aboutinfo;
}
public void setAboutinfo(String aboutinfo) {
this.aboutinfo = aboutinfo;
}
} }
@@ -1,12 +0,0 @@
package cn.hellohao.pojo;
import java.io.File;
/**
* @author Hellohao
* @version 1.0
* @date 2020-04-04 2:12
*/
public class FixedResources {
public static final String LOCPATH = File.separator + "HellohaoData";
}
+26 -5
View File
@@ -4,7 +4,7 @@ public class Images {
// 默认的时间字符串格式 // 默认的时间字符串格式
//id, imgname, imgurl, userid //id, imgname, imgurl, userid
private Integer id; private Long id;
private String imgname; private String imgname;
private String imgurl; private String imgurl;
private Integer userid; private Integer userid;
@@ -35,6 +35,8 @@ public class Images {
private String yyyy; private String yyyy;
private String[] classifuidlist; //类别uid集合 private String[] classifuidlist; //类别uid集合
private String classificationuid; //类别uid集合 private String classificationuid; //类别uid集合
private String idname;
private Integer isRepeat;//如果没有开启查重的时候他是0,开启为1
public Images() { public Images() {
super(); super();
@@ -50,11 +52,12 @@ public class Images {
this.imguid = imguid; this.imguid = imguid;
} }
public Images(Integer id, String imgname, String imgurl, Integer userid, String sizes, String abnormal, Integer source, public Images(Long id, String imgname, String imgurl, Integer userid, String sizes, String abnormal, Integer source,
Integer imgtype, String updatetime, String username, Integer storageType, String starttime, String stoptime, 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 explains, String md5key, String notes, String useridlist, String imguid, String albumtitle,
String password, Integer selecttype,Long countNum,Integer monthNum,String yyyy, String password, Integer selecttype,Long countNum,Integer monthNum,String yyyy,
String format,String about,Integer great,String[] classifuidlist,String classificationuid,String violation) { String format,String about,Integer great,String[] classifuidlist,String classificationuid,String violation,
String idname,Integer isRepeat) {
this.id = id; this.id = id;
this.imgname = imgname; this.imgname = imgname;
this.imgurl = imgurl; this.imgurl = imgurl;
@@ -85,14 +88,16 @@ public class Images {
this.classifuidlist = classifuidlist; this.classifuidlist = classifuidlist;
this.classificationuid = classificationuid; this.classificationuid = classificationuid;
this.violation = violation; this.violation = violation;
this.idname = idname;
this.isRepeat = isRepeat;
} }
public Integer getId() { public Long getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@@ -328,6 +333,22 @@ public class Images {
public void setViolation(String violation) { public void setViolation(String violation) {
this.violation = 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;
}
} }
+5 -81
View File
@@ -1,94 +1,18 @@
package cn.hellohao.pojo; package cn.hellohao.pojo;
import lombok.Data;
@Data
public class Keys { public class Keys {
private Integer id; private Integer id;
private String AccessKey; private String AccessKey;
private String AccessSecret; private String AccessSecret;
private String Endpoint; private String Endpoint;
private String Region;
private String Bucketname; private String Bucketname;
private String RequestAddress; private String RequestAddress;
private Integer storageType; private Integer storageType;
private String keyname; private String keyname;
private String RootPath;//存入的目录
public Keys() {
super();
}
public Keys(Integer id, String accessKey, String accessSecret, String endpoint, String bucketname,
String requestAddress, Integer storageType,String keyname) {
super();
this.id = id;
this.AccessKey = accessKey;
this.AccessSecret = accessSecret;
this.Endpoint = endpoint;
this.Bucketname = bucketname;
this.RequestAddress = requestAddress;
this.storageType = storageType;
this.keyname = keyname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccessKey() {
return AccessKey;
}
public void setAccessKey(String accessKey) {
AccessKey = accessKey;
}
public String getAccessSecret() {
return AccessSecret;
}
public void setAccessSecret(String accessSecret) {
AccessSecret = accessSecret;
}
public String getEndpoint() {
return Endpoint;
}
public void setEndpoint(String endpoint) {
Endpoint = endpoint;
}
public String getBucketname() {
return Bucketname;
}
public void setBucketname(String bucketname) {
Bucketname = bucketname;
}
public String getRequestAddress() {
return RequestAddress;
}
public void setRequestAddress(String requestAddress) {
RequestAddress = requestAddress;
}
public Integer getStorageType() {
return storageType;
}
public void setStorageType(Integer storageType) {
this.storageType = storageType;
}
public String getKeyname() {
return keyname;
}
public void setKeyname(String keyname) {
this.keyname = keyname;
}
} }
+22 -4
View File
@@ -7,10 +7,7 @@ public class User {
//@NotBlank(message = "用户名不能为空") //@NotBlank(message = "用户名不能为空")
// @Length(min = 6, max = 20, message = "用户名需要为 6 - 20 个字符") // @Length(min = 6, max = 20, message = "用户名需要为 6 - 20 个字符")
private String username; private String username;
//@NotBlank(message = "密码不能为空")
private String password; private String password;
// @NotBlank(message = "邮箱不能为空")
//@Email(message = "邮箱格式不正确")
private String email; private String email;
private String birthder; private String birthder;
private Integer level; private Integer level;
@@ -19,6 +16,9 @@ public class User {
private String memory; private String memory;
private Integer groupid; private Integer groupid;
private String groupname; private String groupname;
private String token;
private Long counts;//用户img counts
public User() { public User() {
@@ -26,7 +26,7 @@ public class User {
} }
public User(Integer id, String username, String password, String email, String birthder, Integer level, String uid, public User(Integer id, String username, String password, String email, String birthder, Integer level, String uid,
Integer isok, String memory, Integer groupid,String groupname) { Integer isok, String memory, Integer groupid,String groupname,Long counts,String token) {
this.id = id; this.id = id;
this.username = username; this.username = username;
this.password = password; this.password = password;
@@ -38,6 +38,8 @@ public class User {
this.memory = memory; this.memory = memory;
this.groupid = groupid; this.groupid = groupid;
this.groupname = groupname; this.groupname = groupname;
this.counts = counts;
this.token = token;
} }
public Integer getId() { public Integer getId() {
@@ -127,4 +129,20 @@ public class User {
public void setGroupname(String groupname) { public void setGroupname(String groupname) {
this.groupname = groupname; this.groupname = groupname;
} }
public Long getCounts() {
return counts;
}
public void setCounts(Long counts) {
this.counts = counts;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
} }
@@ -1,20 +0,0 @@
package cn.hellohao.quartz;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
@EnableScheduling
@Component
public class FirstJob{
public void task(){
//System.out.println("任务1执行....");
TempImgTask tempImgTask = new TempImgTask();
try {
tempImgTask.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@@ -1,88 +0,0 @@
package cn.hellohao.quartz;
import cn.hellohao.quartz.FirstJob;
import cn.hellohao.quartz.SecondJob;
import cn.hellohao.quartz.SpringUtil;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
@Configuration
public class QuartzConfigration {
//直接读取properties文件的值
// @Value("${Expression}")
private String Expression = "0 0 1 1 * ?";
// 配置触发器1
@Bean(name = "firstTrigger")
public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail) {
SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
trigger.setJobDetail(firstJobDetail);
// 设置任务启动延迟
trigger.setStartDelay(0);
// 每5秒执行一次
trigger.setRepeatInterval(3600000);//一小时
return trigger;
}
// 配置定时任务1
@Bean(name = "firstJobDetail")
public MethodInvokingJobDetailFactoryBean firstJobDetail() {
FirstJob firstJob = (FirstJob) SpringUtil.getBean(FirstJob.class);
MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
// 是否并发执行
jobDetail.setConcurrent(false);
// 为需要执行的实体类对应的对象
jobDetail.setTargetObject(firstJob);
// 需要执行的方法
jobDetail.setTargetMethod("task");
return jobDetail;
}
// 配置触发器2
@Bean(name = "secondTrigger")
public CronTriggerFactoryBean secondTrigger(JobDetail secondJobDetail) {
CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
trigger.setJobDetail(secondJobDetail);
// cron表达式
trigger.setCronExpression(Expression);
//trigger.setCronExpression("0 0/1 * * * ?");
return trigger;
}
// 配置定时任务2
@Bean(name = "secondJobDetail")
public MethodInvokingJobDetailFactoryBean secondJobDetail() {
SecondJob secondJob = (SecondJob) SpringUtil.getBean(SecondJob.class);
MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
// 是否并发执行
jobDetail.setConcurrent(false);
// 为需要执行的实体类对应的对象
jobDetail.setTargetObject(secondJob);
// 需要执行的方法
jobDetail.setTargetMethod("task");
return jobDetail;
}
// 配置Scheduler
@Bean(name = "scheduler")
public SchedulerFactoryBean schedulerFactory(Trigger firstTrigger, Trigger secondTrigger) {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
// 延时启动,应用启动1秒后
bean.setStartupDelay(1);
// 注册触发器
bean.setTriggers(firstTrigger, secondTrigger);
return bean;
}
}
@@ -0,0 +1,49 @@
package cn.hellohao.quartz;
import cn.hellohao.quartz.job.FirstJob;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
@Configuration
public class QuartzConfiguration {
// 配置定时任务1
@Bean(name = "firstJobDetail")
public MethodInvokingJobDetailFactoryBean firstJobDetail(FirstJob firstJob) {
MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
// 是否并发执行
jobDetail.setConcurrent(true);
// 为需要执行的实体类对应的对象
jobDetail.setTargetObject(firstJob);
// 需要执行的方法
jobDetail.setTargetMethod("task");
return jobDetail;
}
// 配置触发器1
@Bean(name = "firstTrigger")
public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail) {
SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
trigger.setJobDetail(firstJobDetail);
// 设置任务启动延迟
trigger.setStartDelay(0);
// 单位毫秒 60000是一分钟
trigger.setRepeatInterval(60000);
return trigger;
}
@Bean(name = "scheduler")
public SchedulerFactoryBean schedulerFactory(Trigger firstTrigger, Trigger secondTrigger) {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
// 延时启动,应用启动5秒后
bean.setStartupDelay(5);
// 注册触发器
bean.setTriggers(firstTrigger, secondTrigger);
return bean;
}
}
@@ -1,134 +0,0 @@
package cn.hellohao.quartz;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Imgreview;
import cn.hellohao.pojo.Keys;
import cn.hellohao.service.impl.ImgServiceImpl;
import cn.hellohao.service.impl.ImgreviewServiceImpl;
import cn.hellohao.service.impl.KeysServiceImpl;
import cn.hellohao.service.impl.NOSImageupload;
import cn.hellohao.utils.LocUpdateImg;
import cn.hellohao.utils.SpringContextHolder;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/*
单任务执行,并且通过控制器的接口实现时间间隔的动态修改
任务类
* */
//@Configuration
@Component
public class SchedulerTask {
@Autowired
private ImgServiceImpl imgService;
@Autowired
private ImgreviewServiceImpl imgreviewService;
@Autowired
private KeysServiceImpl keysService;
private static AipContentCensor client;
private static SchedulerTask schedulerTask;
@PostConstruct
public void init() {
schedulerTask = this; }
private static void Initializes(Imgreview imgreview) {
client = new AipContentCensor(imgreview.getAppId(), imgreview.getApiKey(), imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
}
public void start(){
//查询鉴黄key
Imgreview imgreview = schedulerTask.imgreviewService.selectByPrimaryKey(1);
if(imgreview.getUsing()==1){
//初始化鉴黄
SchedulerTask.Initializes(imgreview);
//计算出昨天的日期
Date d = new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String oldtime = df.format(new Date(d.getTime() - 1 * 24 * 60 * 60 * 1000));
//服务器获取出这个时间段的值然后遍历
List<Images> imglist= schedulerTask.imgService.gettimeimg(oldtime);
for (Images images : imglist) {
String imgurl = images.getImgurl();
System.err.println("正在鉴定的图片:" + imgurl);
JSONObject res = client.antiPorn(imgurl);
res = client.imageCensorUserDefined(imgurl, EImgType.URL, null);
System.err.println("返回的鉴黄json:"+res.toString());
com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if (conclusionType == 2) {
for (Object datum : data) {
com.alibaba.fastjson.JSONObject imgdata = (com.alibaba.fastjson.JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
//标记图片
Integer ret = schedulerTask.imgService.deleimgname(images.getImgname()); //删除数据库图片信息
//Imgreview imgreview1 =imgreviewService.selectByPrimaryKey(1);
Imgreview imgreview1 = new Imgreview();
imgreview1.setId(1);
Integer count = imgreview.getCount();
System.out.println("违法图片总数:" + count);
imgreview1.setCount(count + 1);
schedulerTask.imgreviewService.updateByPrimaryKeySelective(imgreview1);
Keys key =null;
if(images.getSource()==1){
key =schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delect(key, images.getImgname());
}else if (images.getSource()==2){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectOSS(key, images.getImgname());
}else if(images.getSource()==3){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectUSS(key, images.getImgname());
}else if(images.getSource()==4){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectKODO(key, images.getImgname());
}else if(images.getSource()==5){
LocUpdateImg.deleteLOCImg(images.getImgname());
}else if(images.getSource()==6){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectCOS(key, images.getImgname());
}else if(images.getSource()==7){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectFTP(key, images.getImgname());
}else if(images.getSource()==8){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectUFile(key, images.getImgname());
}else{
System.err.println("未获取到对象存储参数,上传失败。");
}
if (ret == 1) {
System.err.println("存在色情图片,删除成功。");
} else {
System.err.println("存在色情图片,删除失败");
}
}
}
}
}
}
}
}
}
@@ -1,16 +0,0 @@
package cn.hellohao.quartz;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
@EnableScheduling
@Component
public class SecondJob{
public void task() {
//System.out.println("任务2执行....");
SchedulerTask schedulerTask = new SchedulerTask();
schedulerTask.start();
}
}
@@ -1,40 +0,0 @@
package cn.hellohao.quartz;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
@@ -1,150 +0,0 @@
package cn.hellohao.quartz;
import cn.hellohao.pojo.FixedResources;
import cn.hellohao.pojo.Keys;
import cn.hellohao.service.impl.ImgServiceImpl;
import cn.hellohao.service.impl.KeysServiceImpl;
import cn.hellohao.utils.DeleImg;
import cn.hellohao.utils.LocUpdateImg;
import cn.hellohao.utils.Print;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/*
单任务执行,并且通过控制器的接口实现时间间隔的动态修改
任务类
* */
//@Configuration
@Component
public class TempImgTask {
@Autowired
private ImgServiceImpl imgService;
@Autowired
private KeysServiceImpl keysService;
private static TempImgTask tempImgTask;
@PostConstruct
public void init() {
tempImgTask = this;
tempImgTask.imgService = this.imgService;
tempImgTask.keysService = this.keysService;
}
public void start() throws InterruptedException {
File f = new File(FixedResources.LOCPATH);
if (!f.exists()) {
f.mkdirs();
}
List<String> list = new ArrayList<>();
File file = new File(File.separator + "HellohaoData"+File.separator+"img.ini");
//判断文件是否存在
if (file.exists()) {
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));//构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
result.append(System.lineSeparator() + s);
String str = s;
String[] strArr = str.split("\\|");
System.out.println(strArr.length); //这里输出3
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date sd1=new Date();//大时间 当前时间
Date sd2=df.parse(strArr[1]);//小时间
if(sd1.after(sd2)){//等于false时说明图片时间大于或者等于当前时间
Integer ret = tempImgTask.imgService.deleimgname(strArr[0]);//删除库里图片数据
Keys key =null;
if(Integer.parseInt(strArr[2])==1){
key = tempImgTask.keysService.selectKeys(Integer.parseInt(strArr[2]));
tempImgTask.imgService.delect(key,strArr[0]);
}else if (Integer.parseInt(strArr[2])==2){
key = tempImgTask.keysService.selectKeys(Integer.parseInt(strArr[2]));
tempImgTask.imgService.delectOSS(key, strArr[0]);
}else if(Integer.parseInt(strArr[2])==3){
key = tempImgTask.keysService.selectKeys(Integer.parseInt(strArr[2]));
tempImgTask.imgService.delectUSS(key, strArr[0]);
}else if(Integer.parseInt(strArr[2])==4){
key = tempImgTask.keysService.selectKeys(Integer.parseInt(strArr[2]));
tempImgTask.imgService.delectKODO(key, strArr[0]);
}else if(Integer.parseInt(strArr[2])==5){
LocUpdateImg.deleteLOCImg(strArr[0]);
}else if(Integer.parseInt(strArr[2])==6){
key = tempImgTask.keysService.selectKeys(Integer.parseInt(strArr[2]));
tempImgTask.imgService.delectCOS(key,strArr[0]);
}else if(Integer.parseInt(strArr[2])==7){
key = tempImgTask.keysService.selectKeys(Integer.parseInt(strArr[2]));
tempImgTask.imgService.delectFTP(key, strArr[0]);
}else{
System.err.println("未获取到对象存储参数,上传失败。");
}
}else{
//没有过期的临时图片
list.add(s);
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
//return result.toString();
textcr(list);
} else {
//Print.warning("file not exists, 不进行暂存扫描处理");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
clearInfoForFile(File.separator + "HellohaoData"+File.separator+"img.ini");
}
/**
* 清空文件内容
* @param fileName
*/
public static void clearInfoForFile(String fileName) {
//Print.Normal("清空原ini文件");
File file =new File(fileName);
try {
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//遍历没有过期的list文本,依次插入
public static void textcr(List<String> list){
clearInfoForFile(File.separator + "HellohaoData"+File.separator+"img.ini");
//Print.Normal("开始重新插入没有过期的文本");
for (String s : list) {
DeleImg.charu(s);
}
}
}
@@ -0,0 +1,95 @@
package cn.hellohao.quartz.job;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.service.ImgTempService;
import cn.hellohao.service.KeysService;
import cn.hellohao.service.impl.*;
import cn.hellohao.utils.LocUpdateImg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Component
@EnableScheduling
public class FirstJob {
@Autowired
private ImgServiceImpl imgService;
@Autowired
private NOSImageupload nosImageupload;
@Autowired
private OSSImageupload ossImageupload;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private KODOImageupload kodoImageupload;
@Autowired
private USSImageupload ussImageupload;
@Autowired
private S3Imageupload s3Imageupload;
@Autowired
private FtpServiceImpl ftpService;
@Autowired
ImgTempService imgTempService;
@Autowired
KeysService keysService;
private static FirstJob firstJob;
@PostConstruct
public void init() {
firstJob = this;
}
//调用的任务主体
public void task() {
// System.out.println("定时任务.//开始");
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currdate = format.format(new Date());
List<Images> imagesList = imgTempService.selectDelImgUidList(currdate);
if(imagesList.size()==0){
// System.out.println("定时任务.//没有期限图片");
return;
}
for (Images images : imagesList) {
imgTempService.delImgAndExp(images.getImguid());
imgService.deleimgForImgUid(images.getImguid());
Keys keys = keysService.selectKeys(images.getSource());
if(keys.getStorageType()==1){
firstJob.nosImageupload.delNOS(keys.getId(),images);
}else if (keys.getStorageType()==2){
firstJob.ossImageupload.delOSS(keys.getId(), images);
}else if(keys.getStorageType()==3){
firstJob.ussImageupload.delUSS(keys.getId(), images);
}else if(keys.getStorageType()==4){
firstJob.kodoImageupload.delKODO(keys.getId(), images);
}else if(keys.getStorageType()==5){
LocUpdateImg.deleteLOCImg(images);
}else if(keys.getStorageType()==6){
firstJob.cosImageupload.delCOS(keys.getId(),images);
}else if(keys.getStorageType()==7){
firstJob.ftpService.delFTP(keys.getId(), images);
}else if(keys.getStorageType()==8){
firstJob.s3Imageupload.deleS3(keys.getId(), images);
}else{
System.err.println("未获取到对象存储参数,上传失败。");
}
}
}catch (Exception e){
System.err.println("任务查询期限图像发生错误");
e.printStackTrace();
}
}
}
@@ -0,0 +1,18 @@
package cn.hellohao.quartz.job;
import java.text.SimpleDateFormat;
import java.util.Date;
//@Component
//@EnableScheduling
public class ThirdJob {
public void task() {
System.out.println("任务3执行....当前时间为" + dateFormat().format(new Date()));
}
private SimpleDateFormat dateFormat() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
return simpleDateFormat;
}
}
@@ -26,4 +26,6 @@ public interface AlbumService {
List<Album> selectAlbumURLList(Album album); List<Album> selectAlbumURLList(Album album);
Integer selectAlbumCount(Integer userid); Integer selectAlbumCount(Integer userid);
Integer updateAlbum(Album album);
} }
@@ -0,0 +1,12 @@
package cn.hellohao.service;
import cn.hellohao.pojo.AppClient;
import org.springframework.stereotype.Service;
@Service
public interface AppClientService {
AppClient getAppClientData( String id);
Integer editAppClientData(AppClient appClient);
}
@@ -13,12 +13,9 @@ import java.util.List;
*/ */
@Service @Service
public interface CodeService { public interface CodeService {
//查询扩容码
List<Code> selectCode(String value); List<Code> selectCode(String value);
Code selectCodekey(String code); Code selectCodekey(String code);
//添加
Integer addCode(Code code); Integer addCode(Code code);
//删除扩容码
Integer deleteCode(String code); Integer deleteCode(String code);
} }
@@ -0,0 +1,10 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Confdata;
import org.springframework.stereotype.Service;
@Service
public interface ConfdataService {
Confdata selectConfdata(String key);
Integer updateConfdata(Confdata confdata);
}
@@ -1,10 +0,0 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Config;
import org.springframework.stereotype.Service;
@Service
public interface ConfigService {
Config getSourceype();
Integer setSourceype(Config config);
}
@@ -4,14 +4,16 @@ import java.util.Map;
public interface IRedisService { public interface IRedisService {
// 加入元素 // 加入元素
void setValue(String key, Map<String, Object> value); void setValue(String key, Map<String, Object> value);
// 加入元素 // 加入元素
void setValue(String key, String value); void setValue(String key, String value);
// 加入元素 // 加入元素
void setValue(String key, Object value); void setTimeValue(String key, Object value,Long time);
// 获取元素 // 获取元素
Object getMapValue(String key); Object getMapValue(String key);
// 获取元素 // 获取元素
Object getValue(String key); Object getValue(String key);
} // 删除某个值
Boolean removeValue(String key);
}
@@ -1,23 +1,25 @@
package cn.hellohao.service; package cn.hellohao.service;
import java.util.List;
import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Param;
import cn.hellohao.pojo.Images; import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
@Service @Service
public interface ImgService { public interface ImgService {
List<Images> selectimg(Images images); List<Images> selectimg(Images images);
Integer deleimg(Integer id); Integer insertImgData(Images images);
Integer deleimg(Long id);
Integer deleimgForImgUid(String imguid);
Integer countimg(Integer userid); Integer countimg(Integer userid);
Images selectByPrimaryKey(Integer id); Images selectByPrimaryKey(Long id);
Integer counts(Integer userid); Integer counts(Integer userid);
@@ -25,7 +27,7 @@ public interface ImgService {
Integer deleimgname(String imgname); Integer deleimgname(String imgname);
Integer deleall(Integer id); Integer deleall(Long id);
List<Images> gettimeimg(String time); List<Images> gettimeimg(String time);
@@ -35,14 +37,12 @@ public interface ImgService {
Integer md5Count(Images images); Integer md5Count(Images images);
Images selectImgUrlByMD5(String md5key); List<Images> selectImgUrlByMD5(String md5key);
List<Images> RecentlyUploaded(Integer userid); List<Images> RecentlyUploaded(Integer userid);
List<User> RecentlyUser(); List<User> RecentlyUser();
Integer addGreat(Integer id);
List<String> getyyyy(Integer userid); List<String> getyyyy(Integer userid);
List<Images> countByM(Images images); List<Images> countByM(Images images);
@@ -12,6 +12,8 @@ import java.util.List;
@Service @Service
public interface ImgTempService { public interface ImgTempService {
List<Images> selectDelImgUidList(String datatime); List<Images> selectDelImgUidList(String datatime);
Integer delImgAndExp(String imguid); Integer delImgAndExp(String imguid);
Integer insertImgExp(ImgTemp imgDataExp); Integer insertImgExp(ImgTemp imgDataExp);
} }
@@ -9,11 +9,13 @@ import java.util.List;
@Service @Service
public interface KeysService { public interface KeysService {
//查询密钥
Keys selectKeys(Integer id); Keys selectKeys(Integer id);
List<Keys> getStorageName(); List<Keys> getStorageName();
List<Keys> getStorage(); List<Keys> getStorage();
//修改key
Msg updateKey(Keys key); Msg updateKey(Keys key);
List<Keys> getKeys(); List<Keys> getKeys();
} }
@@ -1,9 +0,0 @@
package cn.hellohao.service;
import org.springframework.stereotype.Service;
@Service
public interface NoticeService {
String getNotice();
}
@@ -11,5 +11,6 @@ import org.springframework.stereotype.Service;
@Service @Service
public interface SysConfigService { public interface SysConfigService {
SysConfig getstate(); SysConfig getstate();
Integer setstate(SysConfig sysConfig); Integer setstate(SysConfig sysConfig);
} }
@@ -5,6 +5,8 @@ import org.springframework.stereotype.Service;
@Service @Service
public interface UploadConfigService { public interface UploadConfigService {
UploadConfig getUpdateConfig(); UploadConfig getUpdateConfig();
Integer setUpdateConfig(UploadConfig updateConfig); Integer setUpdateConfig(UploadConfig updateConfig);
} }
@@ -10,10 +10,17 @@ import org.springframework.stereotype.Service;
*/ */
@Service @Service
public interface UserGroupService { public interface UserGroupService {
UserGroup useridgetusergroup(Integer userid); UserGroup useridgetusergroup(Integer userid);
UserGroup idgetusergroup(Integer id); UserGroup idgetusergroup(Integer id);
Integer addusergroup(UserGroup userGroup); Integer addusergroup(UserGroup userGroup);
Integer updateusergroup(UserGroup userGroup); Integer updateusergroup(UserGroup userGroup);
Integer updateusergroupdefault(Integer groupid); Integer updateusergroupdefault(Integer groupid);
Integer deleusergroup(Integer userid); Integer deleusergroup(Integer userid);
} }
@@ -1,32 +1,24 @@
package cn.hellohao.service; package cn.hellohao.service;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User; import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
@Service @Service
public interface UserService { public interface UserService {
//注册
Integer register(User user); Integer register(User user);
//登录
Integer login(String email, String password,String uid); Integer login(String email, String password,String uid);
//获取用户信息 User loginByToken (String token);
User getUsers(User user); User getUsers(User user);
//插入图片
Integer insertimg(Images img);
//修改资料
Integer change(User user); Integer change(User user);
Integer changeUser(User user); Integer changeUser(User user);
//检查用户名是否重复
Integer checkUsername(String username); Integer checkUsername(String username);
Integer getUserTotal(); Integer getUserTotal();
@@ -35,7 +27,6 @@ public interface UserService {
Integer deleuser(Integer id); Integer deleuser(Integer id);
//查询用户名或者邮箱是否存在
Integer countusername(String username); Integer countusername(String username);
Integer countmail(String email); Integer countmail(String email);
@@ -43,8 +34,12 @@ public interface UserService {
Integer uiduser(String uid); Integer uiduser(String uid);
User getUsersMail(String uid); User getUsersMail(String uid);
Integer setisok (User user); Integer setisok (User user);
Integer setmemory(User user); Integer setmemory(User user);
User getUsersid(Integer id); User getUsersid(Integer id);
List<User> getuserlistforgroupid(Integer groupid); List<User> getuserlistforgroupid(Integer groupid);
} }
@@ -1,23 +1,19 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import cn.hellohao.dao.AlbumMapper; import cn.hellohao.dao.AlbumMapper;
import cn.hellohao.dao.ConfigMapper;
import cn.hellohao.dao.ImgAndAlbumMapper; import cn.hellohao.dao.ImgAndAlbumMapper;
import cn.hellohao.dao.ImgMapper; import cn.hellohao.dao.ImgMapper;
import cn.hellohao.exception.CodeException; import cn.hellohao.exception.CodeException;
import cn.hellohao.pojo.Album; import cn.hellohao.pojo.Album;
import cn.hellohao.pojo.Images; import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.ImgAndAlbum; import cn.hellohao.pojo.ImgAndAlbum;
import cn.hellohao.pojo.Msg;
import cn.hellohao.service.AlbumService; import cn.hellohao.service.AlbumService;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.UUID;
/** /**
* @author Hellohao * @author Hellohao
@@ -26,86 +22,85 @@ import java.util.UUID;
*/ */
@Service @Service
public class AlbumServiceImpl implements AlbumService { public class AlbumServiceImpl implements AlbumService {
@Autowired @Autowired AlbumMapper albumMapper;
AlbumMapper albumMapper; @Autowired ImgAndAlbumMapper andAlbumMapper;
@Autowired @Autowired ImgMapper imgMapper;
ImgAndAlbumMapper andAlbumMapper;
@Autowired
ConfigMapper configMapper;
@Autowired
ImgMapper imgMapper;
@Override
@Override public JSONArray getAlbumList(JSONArray array) {
public JSONArray getAlbumList(JSONArray array) { JSONArray jsonArray = new JSONArray();
JSONArray jsonArray = new JSONArray(); for (int i = 0; i < array.size(); i++) {
for (int i = 0; i < array.size(); i++) { Images images = new Images();
Images images = new Images(); images.setImguid(array.getString(i));
images.setImguid(array.getString(i)); jsonArray.add(imgMapper.selectimg(images).get(0));
jsonArray.add(imgMapper.selectimg(images).get(0));
}
return jsonArray;
} }
return jsonArray;
}
@Override @Override
public Album selectAlbum(Album album) { public Album selectAlbum(Album album) {
return albumMapper.selectAlbum(album); return albumMapper.selectAlbum(album);
} }
@Override @Override
public Integer addAlbum(Album album) { public Integer addAlbum(Album album) {
return albumMapper.addAlbum(album); return albumMapper.addAlbum(album);
} }
@Transactional @Transactional
public Integer addAlbumForImgAndAlbumMapper(ImgAndAlbum imgAndAlbum) { public Integer addAlbumForImgAndAlbumMapper(ImgAndAlbum imgAndAlbum) {
Integer tem = 0; Integer tem = 0;
Integer r2 = andAlbumMapper.addImgAndAlbum(imgAndAlbum); Integer r2 = andAlbumMapper.addImgAndAlbum(imgAndAlbum);
if(r2>0){ if (r2 > 0) {
tem = 1; tem = 1;
}else{ } else {
throw new CodeException("插入画廊数据失败,回滚"); throw new CodeException("插入画廊数据失败,回滚");
}
return tem;
} }
return tem;
}
@Override @Override
public Integer deleteAlbum(String albumkey) { public Integer deleteAlbum(String albumkey) {
return albumMapper.deleteAlbum(albumkey); return albumMapper.deleteAlbum(albumkey);
} }
@Override @Override
public List<Album> selectAlbumURLList(Album album) { public List<Album> selectAlbumURLList(Album album) {
return albumMapper.selectAlbumURLList(album); return albumMapper.selectAlbumURLList(album);
} }
@Override @Override
public Integer selectAlbumCount(Integer userid) { public Integer selectAlbumCount(Integer userid) {
return albumMapper.selectAlbumCount(userid); return albumMapper.selectAlbumCount(userid);
} }
@Transactional @Override
public Integer delete(String albumkey) { public Integer updateAlbum(Album album) {
Integer ret1 = albumMapper.deleteAlbum(albumkey); return albumMapper.updateAlbum(album);
if(ret1>0){ }
ret1 = andAlbumMapper.deleteImgAndAlbumForKey(albumkey);
}else{
throw new CodeException("删除画廊失败。");
}
return ret1;
}
@Transactional @Transactional
public Integer deleteAll(String[] albumkeyArr) { public Integer delete(String albumkey) {
Integer ret1 = 0 ; Integer ret1 = albumMapper.deleteAlbum(albumkey);
for (String s : albumkeyArr) { if (ret1 > 0) {
ret1 = albumMapper.deleteAlbum(s); ret1 = andAlbumMapper.deleteImgAndAlbumForKey(albumkey);
if(ret1>0){ } else {
ret1 = andAlbumMapper.deleteImgAndAlbumForKey(s); throw new CodeException("删除画廊失败。");
}else{
throw new CodeException("删除画廊失败。");
}
}
return ret1;
} }
return ret1;
}
@Transactional
public Integer deleteAll(String[] albumkeyArr) {
Integer ret1 = 0;
for (String s : albumkeyArr) {
ret1 = albumMapper.deleteAlbum(s);
if (ret1 > 0) {
ret1 = andAlbumMapper.deleteImgAndAlbumForKey(s);
} else {
throw new CodeException("删除画廊失败。");
}
}
return ret1;
}
} }
@@ -0,0 +1,25 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.AppClientMapper;
import cn.hellohao.pojo.AppClient;
import cn.hellohao.service.AppClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AppClientServiceImpl implements AppClientService {
@Autowired
AppClientMapper appClientMapper;
@Override
public AppClient getAppClientData(String id) {
return appClientMapper.getAppClientData(id);
}
@Override
public Integer editAppClientData(AppClient appClient) {
return appClientMapper.editAppClientData(appClient);
}
}
@@ -1,108 +1,101 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.*;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import com.netease.cloud.services.nos.transfer.TransferManager;
import com.qcloud.cos.COSClient; import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig; import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials; import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials; import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException; import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException; import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*; import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region; import com.qcloud.cos.region.Region;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.util.Map;
import java.util.*;
@Service @Service
public class COSImageupload { public class COSImageupload {
static COSClient cosClient; static COSClient cosClient;
static Keys key; static Keys key;
public ReturnImage ImageuploadCOS(Map<String, File> fileMap, String username,Integer keyID) { public ReturnImage ImageuploadCOS(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage(); ReturnImage returnImage = new ReturnImage();
File file = null; File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
try { try {
for (Map.Entry<String, File> entry : fileMap.entrySet()) { for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid(); String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue(); file = entry.getValue();
try { try {
String bucketName = key.getBucketname(); String bucketName = key.getBucketname();
String userkey =username + "/" + ShortUID + "." + entry.getKey(); String userkey = username + "/" + ShortUIDName + "." + prefix;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, userkey, file); PutObjectRequest putObjectRequest =
new PutObjectRequest(bucketName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
returnImage.setImgname(userkey);
returnImage.setImgurl(key.getRequestAddress() + "/" + userkey);
returnImage.setImgSize(entry.getValue().length());
returnImage.setCode("200");
} catch (CosServiceException serverException) { } catch (CosServiceException serverException) {
returnImage.setCode("400");
serverException.printStackTrace(); serverException.printStackTrace();
} catch (CosClientException clientException) { } catch (CosClientException clientException) {
returnImage.setCode("400");
clientException.printStackTrace(); clientException.printStackTrace();
} }
} }
}catch(Exception e){
e.printStackTrace();
returnImage.setCode("200"); returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
} }
return returnImage; return returnImage;
} }
public static Integer Initialize(Keys k) { public static Integer Initialize(Keys k) {
int ret = -1; int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null if (StringUtils.isBlank(k.getAccessKey())
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) { || StringUtils.isBlank(k.getAccessSecret())
if (!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") || StringUtils.isBlank(k.getEndpoint())
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("")) { || StringUtils.isBlank(k.getBucketname())
String secretId = k.getAccessKey(); || StringUtils.isBlank(k.getRequestAddress())) {
String secretKey = k.getAccessSecret(); return -1;
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); }
Region region = new Region(k.getEndpoint()); String secretId = k.getAccessKey();
ClientConfig clientConfig = new ClientConfig(region); String secretKey = k.getAccessSecret();
COSClient cosClient = new COSClient(cred, clientConfig); COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); Region region = new Region(k.getEndpoint());
listObjectsRequest.setBucketName(k.getBucketname()); ClientConfig clientConfig = new ClientConfig(region);
listObjectsRequest.setDelimiter("/"); COSClient cos = new COSClient(cred, clientConfig);
listObjectsRequest.setMaxKeys(1); ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
ObjectListing objectListing = null; listObjectsRequest.setBucketName(k.getBucketname());
try { listObjectsRequest.setDelimiter("/");
objectListing = cosClient.listObjects(listObjectsRequest); listObjectsRequest.setMaxKeys(1);
ret = 1; ObjectListing objectListing = null;
cosClient = cosClient; try {
key = k; objectListing = cos.listObjects(listObjectsRequest);
} catch (Exception e) { ret = 1;
System.out.println("COS Object Is null"); cosClient = cos;
ret = -1; key = k;
} } catch (Exception e) {
} System.out.println("COS Object Is null");
ret = -1;
} }
return ret; return ret;
} }
public Boolean delCOS(Integer keyID, String fileName) { public Boolean delCOS(Integer keyID, Images images) {
boolean b = true; boolean b = true;
try { try {
cosClient.deleteObject(key.getBucketname(), fileName); cosClient.deleteObject(key.getBucketname(), images.getImgname());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
b = false; b = false;
} }
return b ; return b;
} }
} }
@@ -2,19 +2,9 @@ package cn.hellohao.service.impl;
import cn.hellohao.dao.*; import cn.hellohao.dao.*;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.pojo.vo.PageResultBean; import cn.hellohao.service.ImgTempService;
import cn.hellohao.service.ImgAndAlbumService;
import cn.hellohao.service.SysConfigService;
import cn.hellohao.utils.*; import cn.hellohao.utils.*;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.coobird.thumbnailator.filters.Watermark;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -34,49 +24,25 @@ import java.util.*;
@Service @Service
public class ClientService { public class ClientService {
@Autowired @Autowired private UserMapper userMapper;
private ImgAndAlbumService imgAndAlbumService; @Autowired private KeysMapper keysMapper;
@Autowired @Autowired private UploadConfigMapper uploadConfigMapper;
private NOSImageupload nOSImageupload; @Autowired private ImgMapper imgMapper;
@Autowired @Autowired private ImgreviewMapper imgreviewMapper;
private OSSImageupload ossImageupload; @Autowired private ImgTempService imgTempService;
@Autowired @Autowired private GetSource getSource;
private USSImageupload ussImageupload; @Autowired private ImgViolationJudgeServiceImpl imgViolationJudgeService;
@Autowired
private KODOImageupload kodoImageupload;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private SysConfigService sysConfigService;
@Autowired
private FTPImageupload ftpImageupload;
@Autowired
private UFileImageupload uFileImageupload;
@Autowired
private UserMapper userMapper;
@Autowired
private KeysMapper keysMapper;
@Autowired
private ConfigMapper configMapper;
@Autowired
private UploadConfigMapper uploadConfigMapper;
@Autowired
private NoticeMapper noticeMapper;
@Autowired
private ImgMapper imgMapper;
@Autowired
ImgreviewMapper imgreviewMapper;
public Msg uploadImg(
public Msg uploadImg(HttpServletRequest request, MultipartFile multipartFile, String email, String pass ){ HttpServletRequest request, MultipartFile multipartFile, String email, String pass,Integer setday) {
Msg msg = new Msg(); Msg msg = new Msg();
try { try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String imageFileName = "未命名图像";
Integer sourceKeyId = 0; Integer sourceKeyId = 0;
FileInputStream fis = null; FileInputStream fis = null;
String md5key = null; String md5key = null;
Integer setday = 0;
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
Config config = configMapper.getSourceype();
String userip = GetIPS.getIpAddr(request); String userip = GetIPS.getIpAddr(request);
UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig(); UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig();
if (uploadConfig.getApi() != 1) { if (uploadConfig.getApi() != 1) {
@@ -84,6 +50,7 @@ public class ClientService {
msg.setInfo("管理员关闭了API接口"); msg.setInfo("管理员关闭了API接口");
return msg; return msg;
} }
imageFileName = multipartFile.getOriginalFilename();
File file = SetFiles.changeFile_new(multipartFile); File file = SetFiles.changeFile_new(multipartFile);
User u2 = new User(); User u2 = new User();
if (!file.exists() || email == null || pass == null) { if (!file.exists() || email == null || pass == null) {
@@ -94,14 +61,12 @@ public class ClientService {
u2.setEmail(email); u2.setEmail(email);
u2.setPassword(Base64Encryption.encryptBASE64(pass.getBytes())); u2.setPassword(Base64Encryption.encryptBASE64(pass.getBytes()));
User u = userMapper.getUsers(u2); User u = userMapper.getUsers(u2);
//判断用户的账号密码是否存在(正确)
if (null == u || u.getIsok() != 1) { if (null == u || u.getIsok() != 1) {
msg.setCode("4006"); msg.setCode("4006");
msg.setInfo("用户信息不正确,账号异常"); msg.setInfo("用户信息不正确,账号异常");
return msg; return msg;
} }
String imguid = UUID.randomUUID().toString().replace("-", ""); String imguid = UUID.randomUUID().toString().replace("-", "");
//判断上传前的一些用户限制信息
Msg msg1 = updateImgCheck(u, uploadConfig); Msg msg1 = updateImgCheck(u, uploadConfig);
if (!msg1.getCode().equals("300")) { if (!msg1.getCode().equals("300")) {
return msg1; return msg1;
@@ -128,9 +93,8 @@ public class ClientService {
e.printStackTrace(); e.printStackTrace();
System.out.println("未获取到图片的MD5,成成UUID"); System.out.println("未获取到图片的MD5,成成UUID");
} }
Msg fileMiME = TypeDict.FileMiME(file, uploadConfig.getSuffix()); Msg fileMiME = TypeDict.FileMiME(file);
if (!fileMiME.getCode().equals("200")) { if (!fileMiME.getCode().equals("200")) {
//非图像文本
msg.setCode("4009"); msg.setCode("4009");
msg.setInfo(fileMiME.getInfo()); msg.setInfo(fileMiME.getInfo());
return msg; return msg;
@@ -149,115 +113,130 @@ public class ClientService {
} }
} }
} }
//判断图片是否存在 Images imgObj = new Images();
if(Integer.valueOf(sysConfigService.getstate().getCheckduplicate())==1) { String imgnameEd = null;
Map<Map<String, String>, File> map = new HashMap<>();
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(key.getRequestAddress() + "/" + imgnameEd);
}
imgObj.setSizes(Long.toString(file.length()));
}else{
msg.setInfo("未获取到指定图像:110503");
msg.setCode("110503");
return msg;
}
imgObj.setUpdatetime(df.format(new Date()));
imgObj.setSource(key.getId());
imgObj.setUserid(u == null ? 0 : u.getId());
if (setday == 1 || setday == 3 || setday == 7 || setday == 30) {
imgObj.setImgtype(1);
ImgTemp imgDataExp = new ImgTemp();
imgDataExp.setDeltime(UploadServicel.plusDay(setday));
imgDataExp.setImguid(imguid);
imgTempService.insertImgExp(imgDataExp);
} else {
imgObj.setImgtype(0);
}
imgObj.setAbnormal(userip);
imgObj.setMd5key(md5key);
imgObj.setImguid(imguid);
imgObj.setFormat(fileMiME.getData().toString());
imgObj.setIdname(imageFileName);
Integer insertRet = imgMapper.insertImgData(imgObj);
if (insertRet == 0) {
Images imaOBJ = new Images(); Images imaOBJ = new Images();
imaOBJ.setMd5key(md5key); imaOBJ.setMd5key(md5key);
imaOBJ.setUserid(u.getId()); imaOBJ.setUserid(u == null ? 0 : u.getId());
if (imgMapper.md5Count(imaOBJ) > 0) { List<Images> images = imgMapper.selectImgUrlByMD5(md5key);
Images images = imgMapper.selectImgUrlByMD5(md5key); if (images.size() > 0) {
jsonObject.put("url", images.getImgurl()); jsonObject.put("url", images.get(0).getImgurl());
jsonObject.put("name", file.getName()); jsonObject.put("name", file.getName());
jsonObject.put("size", images.getSizes()); jsonObject.put("size", images.get(0).getSizes());
msg.setData(jsonObject); msg.setData(jsonObject);
return msg; return msg;
} else {
msg.setInfo("未获取到指定图像");
msg.setCode("110501");
return msg;
} }
} }
Map<String, File> map = new HashMap<>();
String fileName = file.getName();
if (file.exists()) {
map.put(prefix, file);
}
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
Map<ReturnImage, Integer> m = null; ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
ReturnImage returnImage = GetSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
Images img = new Images();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (returnImage.getCode().equals("200")) { if (returnImage.getCode().equals("200")) {
String imgurl = returnImage.getImgurl();
Long imgsize = returnImage.getImgSize();
String imgname = returnImage.getImgname();
img.setImgurl(imgurl);
img.setUpdatetime(df.format(new Date()));
img.setSource(key.getId());
img.setUserid(u == null ? 0 : u.getId());
img.setSizes(imgsize.toString());
if (uploadConfig.getUrltype() == 2) {
img.setImgname(imgname);
} else {
img.setImgname(SetText.getSubString(imgname, key.getRequestAddress() + "/", ""));
}
img.setImgtype(setday > 0 ? 1 : 0);
img.setAbnormal(userip);
img.setMd5key(md5key);
img.setImguid(imguid);
img.setFormat(fileMiME.getData().toString());
userMapper.insertimg(img);
long etime = System.currentTimeMillis(); long etime = System.currentTimeMillis();
Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms"); Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms");
jsonObject.put("url", img.getImgurl()); jsonObject.put("url", imgObj.getImgurl());
jsonObject.put("name", imgname); jsonObject.put("name", imgObj.getImgname());
jsonObject.put("size", img.getSizes()); jsonObject.put("size", imgObj.getSizes());
//启动鉴黄线程 imgViolationJudgeService.LegalImageCheck(imgObj,key);
new Thread(() -> {
LegalImageCheck(img);
}).start();
} else { } else {
imgMapper.deleimgForImgUid(imgObj.getImguid());
msg.setCode("5001"); msg.setCode("5001");
msg.setInfo("上传服务内部错误"); msg.setInfo("上传服务内部错误");
return msg; return msg;
} }
file.delete(); file.delete();
msg.setData(jsonObject); msg.setData(jsonObject);
// 新代码结束=========
return msg; return msg;
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setCode("5001"); msg.setCode("5001");
msg.setInfo("Error for server:500"); msg.setInfo("Error for server:500");
return msg; 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; //上传用户或游客的所属分组 private Msg updateImgCheck(User user, UploadConfig uploadConfig) {
public static Long memory;//上传用户或者游客的分配容量 memory Msg msg = new Msg();
public static Long TotleMemory;//用户或者游客下可使用的总容量 //maxsize
public static Long UsedTotleMemory;//用户或者游客已经用掉的总容量 //usermemory
public static String updatePath="tourist";
//判断用户 或 游客 当前上传图片的一系列校验
private Msg updateImgCheck(User user, UploadConfig uploadConfig){
final Msg msg = new Msg();
java.text.DateFormat dateFormat = null; java.text.DateFormat dateFormat = null;
try { try {
dateFormat = new SimpleDateFormat("yyyy/MM/dd"); dateFormat = new SimpleDateFormat("yyyy/MM/dd");
if (user == null) { if (user == null) {
//用户没有登陆,值判断游客能不能上传即可 if (uploadConfig.getIsupdate() != 1) {
if(uploadConfig.getIsupdate()!=1){
msg.setCode("1000"); msg.setCode("1000");
msg.setInfo("系统已禁用游客上传"); msg.setInfo("系统已禁用游客上传");
return msg; return msg;
} }
group = GetCurrentSource.GetSource(null); group = GetCurrentSource.GetSource(null);
memory = Long.valueOf(uploadConfig.getVisitormemory());//单位 B 游客设置总量 memory = Long.valueOf(uploadConfig.getVisitormemory()); // 单位 B 游客设置总量
TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists());//单位 B 游客单文件大小 TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists()); // 单位 B 游客单文件大小
UsedTotleMemory = imgMapper.getusermemory(0)==null?0L : imgMapper.getusermemory(0);//单位 B UsedTotleMemory =
imgMapper.getusermemory(0) == null
? 0L
: imgMapper.getusermemory(0); // 单位 B
} else { } else {
//判断用户能不能上传 // 判断用户能不能上传
if(uploadConfig.getUserclose()!=1){ if (uploadConfig.getUserclose() != 1) {
msg.setCode("1001"); msg.setCode("1001");
msg.setInfo("系统已禁用上传功能"); msg.setInfo("系统已禁用上传功能");
return msg; return msg;
} }
updatePath = user.getUsername(); updatePath = user.getUsername();
group= GetCurrentSource.GetSource(user.getId()); group = GetCurrentSource.GetSource(user.getId());
memory = Long.valueOf(user.getMemory())*1024*1024;//单位 B memory = Long.valueOf(user.getMemory()); // 单位 B
TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser());//单位 B TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser()); // 单位 B
UsedTotleMemory = imgMapper.getusermemory(user.getId())==null?0L:imgMapper.getusermemory(user.getId());//单位 B UsedTotleMemory =
imgMapper.getusermemory(user.getId()) == null
? 0L
: imgMapper.getusermemory(user.getId()); // 单位 B
} }
//判断上传的图片目录结构类型 // 判断上传的图片目录结构类型
if (uploadConfig.getUrltype() == 2) { if (uploadConfig.getUrltype() == 2) {
updatePath = dateFormat.format(new Date()); updatePath = dateFormat.format(new Date());
} }
@@ -269,63 +248,4 @@ public class ClientService {
return msg; return msg;
} }
//图片鉴黄
private synchronized void LegalImageCheck(Images images){
System.out.println("非法图像鉴别进程启动");
Imgreview imgreview = null;
try {
imgreview = imgreviewMapper.selectByusing(1);
} catch (Exception e) {
Print.warning("获取鉴别程序的时候发生错误");
e.printStackTrace();
}
LegalImageCheckForBaiDu(imgreview,images);
}
private void LegalImageCheckForBaiDu(Imgreview imgreview,Images images){
if(imgreview.getUsing()==1){
try {
AipContentCensor client = new AipContentCensor(imgreview.getAppId(), imgreview.getApiKey(), imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(5000);
client.setSocketTimeoutInMillis(30000);
org.json.JSONObject res = client.antiPorn(images.getImgurl());
res = client.imageCensorUserDefined(images.getImgurl(), EImgType.URL, null);
com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
JSONObject jsonObject = (JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if(conclusionType!=null){
if (conclusionType == 2) {
for (Object datum : data) {
JSONObject imgdata = (JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
Images img = new Images();
img.setImgname(images.getImgname());
img.setViolation("1[1]");//数字是鉴别平台的主键ID,括号是非法的类型,参考上面的注释
imgMapper.setImg(img);
Imgreview imgv = new Imgreview();
imgv.setId(1);
Integer count = imgreview.getCount();
System.out.println("违法图片总数:" + count);
imgv.setCount(count + 1);
imgreviewMapper.updateByPrimaryKeySelective(imgv);
System.err.println("存在非法图片,进行处理操作");
}
}
}
}
}
}catch (Exception e){
System.out.println("图像鉴黄线程执行过程中出现异常");
e.printStackTrace();
}
}
}
} }
@@ -19,7 +19,6 @@ public class CodeServiceImpl implements CodeService {
@Autowired @Autowired
private CodeMapper codeMapper; private CodeMapper codeMapper;
@Override @Override
public List<Code> selectCode(String value) { public List<Code> selectCode(String value) {
return codeMapper.selectCode(value); return codeMapper.selectCode(value);
@@ -0,0 +1,23 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ConfdataMapper;
import cn.hellohao.pojo.Confdata;
import cn.hellohao.service.ConfdataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfdataServiceImpl implements ConfdataService {
@Autowired
private ConfdataMapper confdataMapper;
@Override
public Confdata selectConfdata(String key) {
return confdataMapper.selectConfdata(key);
}
@Override
public Integer updateConfdata(Confdata confdata) {
return confdataMapper.updateConfdata(confdata);
}
}
@@ -1,23 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ConfigMapper;
import cn.hellohao.pojo.Config;
import cn.hellohao.pojo.Images;
import cn.hellohao.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfigServiceImpl implements ConfigService {
@Autowired
private ConfigMapper configMapper;
@Override
public Config getSourceype() {
return configMapper.getSourceype();
}
@Override
public Integer setSourceype(Config config) {
return configMapper.setSourceype(config);
}
}
@@ -10,6 +10,7 @@ import org.springframework.stereotype.Service;
public class EmailServiceImpl implements EmailConfigService { public class EmailServiceImpl implements EmailConfigService {
@Autowired @Autowired
EmailConfigMapper emailConfigMapper; EmailConfigMapper emailConfigMapper;
@Override @Override
public EmailConfig getemail() { public EmailConfig getemail() {
return emailConfigMapper.getemail(); return emailConfigMapper.getemail();
@@ -1,136 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
@Service
public class FTPImageupload {
static FTPClient ftpClient1 ;
static Keys key;
public ReturnImage ImageuploadFTP(Map<String, File> fileMap, String username,Integer keyID) {
ReturnImage returnImage = new ReturnImage();
Keys key = null;
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
boolean flag = ftps.open();
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ftps.mkDir(File.separator+username);
try {
for (Map.Entry<String, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid();
file = entry.getValue();
String userkey =username + "/"+ ShortUID + "." + entry.getKey();
if (flag) {
boolean isUpload = ftps.upload(file, "/" + userkey, "");
if(isUpload){
returnImage.setImgname(userkey);
returnImage.setImgurl(key.getRequestAddress() + "/"+ userkey);
returnImage.setImgSize(entry.getValue().length());
returnImage.setCode("200");
}else{
returnImage.setCode("500");
}
}
Print.Normal("要上传的文件路径:/"+userkey);
}
}catch (Exception e){
e.printStackTrace();
returnImage.setCode("500");
// ImgUrl.put(null, 500);
}
return returnImage;
}
//初始化FTP对象存储
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") && !k.getRequestAddress().equals("") ) {
FTPClient ftp = new FTPClient();
ftp.setConnectTimeout(0);
int flag = k.getEndpoint().indexOf(":");
if(flag>0){
String[] host = k.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if(!ftp.isConnected()){
ftp.connect(h,p);
}
ftp.login(k.getAccessKey(), k.getAccessSecret());
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("FTP Object Is null");
ftp.disconnect();
return -1;
}
ret = 1;
key = k;
// KeyObjectMap objectMap = new KeyObjectMap(ftp,k);
} catch (IOException e) {
System.out.println("FTP Object Is null");
return -1;
}
}
}
}
return ret;
}
public static void fuzhi(String p1,String p2){
String a=p1;
try{
File afile=new File(a);
File bfile=new File(p2);//定义一个复制后的文件路径
bfile.createNewFile();//新建文件
FileInputStream c=new FileInputStream(afile);//定义FileInputStream对象
FileOutputStream d=new FileOutputStream(bfile);//定义FileOutputStream对象
byte[] date=new byte[512];//定义一个byte数组
int i=0;
while((i=c.read(date))>0){//判断有没有读取到文件末尾
d.write(date);
}
c.close();
d.close();
System.out.println("文件复制成功");}
catch(IOException e){
e.printStackTrace();
}
}
public Boolean delFTP(Integer keyID, String fileName) {
boolean b = true;
try {
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
//创建FTP客户端,所有的操作都基于FTPClinet
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
ftps.open();
b = ftps.deleteFile(fileName);
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -0,0 +1,107 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class FtpServiceImpl {
private Keys key;
public static int Initialize(Keys k) {
int ret = -1;
try{
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getRequestAddress())){
return -1;
}
Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8");
String[] hostArr = k.getEndpoint().split("\\:");
String host = hostArr[0];
Integer port = Integer.parseInt(hostArr[1]);
Ftp ftp = new Ftp(host, port, k.getAccessKey(), k.getAccessSecret(), charset);
ftp.getClient().type(FTP.BINARY_FILE_TYPE);
ftp.setMode(FtpMode.Passive);
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public ReturnImage FtpUploadFile(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
Ftp ftp = null;
try {
if (null == key) {
System.out.println("FTP = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8");
String[] hostArr = key.getEndpoint().split("\\:");
String host = hostArr[0];
Integer port = Integer.parseInt(hostArr[1]);
ftp = new Ftp(host, port, key.getAccessKey(), key.getAccessSecret(), charset);
ftp.getClient().type(FTP.BINARY_FILE_TYPE);
ftp.setMode(FtpMode.Passive);
} catch (Exception e) {
e.printStackTrace();
System.out.println("FTP = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
File file = null;
try {
for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
boolean isUpload = ftp.upload(
"/" + username,
ShortUIDName + "." + prefix,
file);
if (!isUpload) {
returnImage.setCode("400");
}
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
}
return returnImage;
}
public Boolean delFTP(Integer keyID, Images images) {
boolean b = true;
Ftp ftp = null;
try {
Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8");
String[] hostArr = key.getEndpoint().split("\\:");
String host = hostArr[0];
Integer port = Integer.parseInt(hostArr[1]);
ftp = new Ftp(host, port, key.getAccessKey(), key.getAccessSecret(), charset);
b = ftp.delFile(images.getImgname());
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -88,8 +88,8 @@ public class GroupServiceImpl implements GroupService {
if(group.getUsertype()!=0){ if(group.getUsertype()!=0){
Group groupFroUserType = groupMapper.getGroupFroUserType(group.getUsertype()); Group groupFroUserType = groupMapper.getGroupFroUserType(group.getUsertype());
if(groupFroUserType!=null){ if(groupFroUserType!=null){
if(groupFroUserType.getUsertype()==group.getUsertype()){ if(groupFroUserType.getUsertype().equals(group.getUsertype())){
if(groupFroUserType.getId()==group.getId()){ if(groupFroUserType.getId().equals(group.getId())){
groupMapper.setgroup(group); groupMapper.setgroup(group);
msg.setInfo("修改成功"); msg.setInfo("修改成功");
}else{ }else{
@@ -1,48 +1,17 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cn.hellohao.pojo.User;
import cn.hellohao.utils.Print;
import com.UpYun;
import com.aliyun.oss.OSSClient;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.region.Region;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.upyun.UpException;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.Bucket;
import com.netease.cloud.services.nos.model.CannedAccessControlList;
import com.netease.cloud.services.nos.transfer.TransferManager;
import cn.hellohao.dao.ImgMapper; import cn.hellohao.dao.ImgMapper;
import cn.hellohao.pojo.Images; import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.User;
import cn.hellohao.service.ImgService; import cn.hellohao.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource; import java.util.List;
@Service @Service
public class ImgServiceImpl implements ImgService { public class ImgServiceImpl implements ImgService {
@Autowired @Autowired
//@Resource
private ImgMapper imgMapper; private ImgMapper imgMapper;
@Override @Override
@@ -52,122 +21,25 @@ public class ImgServiceImpl implements ImgService {
} }
@Override @Override
public Integer deleimg(Integer id) { public Integer insertImgData(Images images) {
return imgMapper.insertImgData(images);
}
@Override
public Integer deleimg(Long id) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return imgMapper.deleimg(id); return imgMapper.deleimg(id);
} }
@Override
public Integer deleimgForImgUid(String imguid) {
return imgMapper.deleimgForImgUid(imguid);
}
public Images selectByPrimaryKey(Integer id) { public Images selectByPrimaryKey(Long id) {
return imgMapper.selectByPrimaryKey(id); return imgMapper.selectByPrimaryKey(id);
} }
//删除对象存储的图片文件
public void delect(Keys key, String fileName) {
// 初始化
Credentials credentials = new BasicCredentials(key.getAccessKey(), key.getAccessSecret());
NosClient nosClient = new NosClient(credentials);
nosClient.setEndpoint(key.getEndpoint());
// 初始化TransferManager
TransferManager transferManager = new TransferManager(nosClient);
//列举桶
ArrayList bucketList = new ArrayList();
String tname = "";
for (Bucket bucket : nosClient.listBuckets()) {
bucketList.add(bucket.getName());
}
for (Object object : bucketList) {
tname = object.toString();
//查看桶的ACL
CannedAccessControlList acl = nosClient.getBucketAcl(object.toString());
}
//这种方法不能删除指定文件夹下的文件
boolean isExist = nosClient.doesObjectExist(tname, fileName, null);
System.out.println("文件是否存在:" + isExist);
if (isExist) {
nosClient.deleteObject(tname, fileName);
}
}
public void delectOSS(Keys key, String fileName) {
String endpoint = key.getEndpoint();
String accessKeyId = key.getAccessKey();
String accessKeySecret = key.getAccessSecret();
String bucketName = key.getBucketname();
String objectName = fileName;
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.deleteObject(bucketName, objectName);
ossClient.shutdown();
}
//删除USS对象存储的图片文件
public void delectUSS(Keys key, String fileName) {
UpYun upyun = new UpYun(key.getBucketname(), key.getAccessKey(), key.getAccessSecret());
try {
boolean result = upyun.deleteFile(fileName, null);
} catch (IOException e) {
e.printStackTrace();
} catch (UpException e) {
e.printStackTrace();
}
}
public void delectUFile(Keys key, String fileName) {
UpYun upyun = new UpYun(key.getBucketname(), key.getAccessKey(), key.getAccessSecret());
try {
boolean result = upyun.deleteFile(fileName, null);
} catch (IOException e) {
e.printStackTrace();
} catch (UpException e) {
e.printStackTrace();
}
}
public void delectKODO(Keys key, String fileName) {
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());}
Auth auth = Auth.create(key.getAccessKey(), key.getAccessSecret());
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(key.getBucketname(), fileName);
} catch (QiniuException ex) {
//如果遇到异常,说明删除失败
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
}
//删除COS对象存储的图片文件
public void delectCOS(Keys key, String fileName) {
COSCredentials cred = new BasicCOSCredentials(key.getAccessKey(), key.getAccessSecret());
Region region = new Region(key.getEndpoint());
ClientConfig clientConfig = new ClientConfig(region);
COSClient cosClient= new COSClient(cred, clientConfig);
try {
String bucketName = key.getBucketname();
String userkey = fileName;
cosClient.deleteObject(key.getBucketname(), userkey);
} catch (CosServiceException serverException) {
serverException.printStackTrace();
} catch (CosClientException clientException) {
clientException.printStackTrace();
}
}
public void delectFTP(Keys key, String fileName) {
FTPClient ftp = new FTPClient();
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if(!ftp.isConnected()){
ftp.connect(h,p);
}
ftp.login(key.getAccessKey(), key.getAccessSecret());
ftp.deleteFile(fileName);
} catch (IOException e) {
e.printStackTrace();
Print.warning("删除FTP存储的图片失败");
}
}
@Override @Override
public Integer counts(Integer userid) { public Integer counts(Integer userid) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@@ -191,7 +63,7 @@ public class ImgServiceImpl implements ImgService {
} }
@Override @Override
public Integer deleall(Integer id) { public Integer deleall(Long id) {
return imgMapper.deleall(id); return imgMapper.deleall(id);
} }
@@ -216,7 +88,7 @@ public class ImgServiceImpl implements ImgService {
} }
@Override @Override
public Images selectImgUrlByMD5(String md5key) { public List<Images> selectImgUrlByMD5(String md5key) {
return imgMapper.selectImgUrlByMD5(md5key); return imgMapper.selectImgUrlByMD5(md5key);
} }
@@ -230,10 +102,6 @@ public class ImgServiceImpl implements ImgService {
return imgMapper.RecentlyUser(); return imgMapper.RecentlyUser();
} }
@Override
public Integer addGreat(Integer id) {
return imgMapper.addGreat(id);
}
public List<String> getyyyy(Integer userid){ public List<String> getyyyy(Integer userid){
return imgMapper.getyyyy(userid); return imgMapper.getyyyy(userid);
@@ -0,0 +1,116 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ImgMapper;
import cn.hellohao.dao.ImgreviewMapper;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Imgreview;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.utils.FirstRun;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ImgViolationJudgeServiceImpl {
private static Logger logger = LoggerFactory.getLogger(FirstRun.class);
@Autowired
ImgreviewServiceImpl imgreviewService;
@Autowired ImgMapper imgMapper;
@Autowired deleImages deleimages;
@Autowired private ImgreviewMapper imgreviewMapper;
//synchronized
@Async("taskExecutor")
public void LegalImageCheck(Images images, Keys keys) {
Imgreview imgreview = null;
try {
imgreview = imgreviewService.selectByusing(1);
} catch (Exception e) {
logger.error("获取鉴别程序的时候发生错误");
e.printStackTrace();
}
// 判断哪个鉴别平台
if (null != imgreview) {
LegalImageCheckForBaiDu(imgreview, images, keys);
}
}
private void LegalImageCheckForBaiDu(Imgreview imgreview, Images images, Keys keys) {
// Imgreview imgreview = imgreviewService.selectByPrimaryKey(1);
if (imgreview.getUsing() == 1) {
logger.info("非法图像鉴别进程启动-BaiDu");
try {
AipContentCensor client =
new AipContentCensor(
imgreview.getAppId(),
imgreview.getApiKey(),
imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(5000);
client.setSocketTimeoutInMillis(30000);
// res = client.antiPorn(images.getImgurl());
org.json.JSONObject res = client.imageCensorUserDefined(images.getImgurl(), EImgType.URL, null);
logger.info("返回的鉴黄json:" + res.toString());
com.alibaba.fastjson.JSONArray jsonArray =
JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
JSONObject jsonObject =
(JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if (conclusionType != null) {
if (conclusionType == 2) {
// 1:合规,2:不合规,3:疑似,4:审核失败
for (Object datum : data) {
JSONObject imgdata =
(JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
logger.info("存在非法图片,进行处理操作");
// type参数
// 0:百度官方违禁图库、1:色情识别、2:暴恐识别、3:恶心图识别、4:广告检测、5:政治敏感识别、6:图像质量检测、7:用户图像黑名单、8:用户图像白名单、10:用户头像审核、11:百度官方违禁词库、12:图文审核、13:自定义文本黑名单、14:自定义文本白名单、15:EasyDL自定义模型、16:敏感旗帜标志识别、21:不良场景识别、24:直播场景审核
// 存在非法图片,进行处理操作
Images img = new Images();
img.setImgname(images.getImgname());
img.setViolation("1[1]"); // 数字是鉴别平台的主键ID,括号是非法的类型,参考上面的注释
imgMapper.setImg(img);
// 计入总数
Imgreview imgv = new Imgreview();
imgv.setId(1);
Integer count = imgreview.getCount();
imgv.setCount(count + 1);
imgreviewMapper.updateByPrimaryKeySelective(imgv);
Images imgObj =
imgMapper.selectImgUrlByImgUID(images.getImguid());
Msg dele = deleimages.dele2(Long.toString(imgObj.getId()));
List<Long> ids = (List<Long>) dele.getData();
if (!ids.contains(imgObj.getId())) {
logger.error("检测到违规图像,但是数据库删除失败");
}
}
}
}
}
}
} catch (Exception e) {
logger.error("图像鉴黄线程执行过程中出现异常");
e.printStackTrace();
}
}
}
}
@@ -4,6 +4,8 @@ import cn.hellohao.auth.filter.SubjectFilter;
import cn.hellohao.dao.KeysMapper; import cn.hellohao.dao.KeysMapper;
import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.Keys;
import cn.hellohao.utils.Print; import cn.hellohao.utils.Print;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
@@ -23,6 +25,7 @@ import java.util.List;
@Order(2) @Order(2)
public class InitializationStorage implements CommandLineRunner { public class InitializationStorage implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(InitializationStorage.class);
@Value("${CROS_ALLOWED_ORIGINS}") @Value("${CROS_ALLOWED_ORIGINS}")
private String allowedOrigins; private String allowedOrigins;
@@ -30,7 +33,7 @@ public class InitializationStorage implements CommandLineRunner {
private KeysMapper keysMapper; private KeysMapper keysMapper;
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) {
SubjectFilter.WEBHOST = allowedOrigins; SubjectFilter.WEBHOST = allowedOrigins;
String name = ManagementFactory.getRuntimeMXBean().getName(); String name = ManagementFactory.getRuntimeMXBean().getName();
String pid = name.split("@")[0]; String pid = name.split("@")[0];
@@ -41,21 +44,20 @@ public class InitializationStorage implements CommandLineRunner {
List<Keys> keylist = keysMapper.getKeys(); List<Keys> keylist = keysMapper.getKeys();
for (Keys key : keylist) { for (Keys key : keylist) {
if(key.getStorageType()!=0 && key.getStorageType()!=null){ if(key.getStorageType()!=0 && key.getStorageType()!=null){
int ret =0;
if(key.getStorageType()==1){ if(key.getStorageType()==1){
ret =NOSImageupload.Initialize(key); NOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){ }else if (key.getStorageType()==2){
ret =OSSImageupload.Initialize(key); OSSImageupload.Initialize(key);
}else if(key.getStorageType()==3){ }else if(key.getStorageType()==3){
ret = USSImageupload.Initialize(key); USSImageupload.Initialize(key);
}else if(key.getStorageType()==4){ }else if(key.getStorageType()==4){
ret = KODOImageupload.Initialize(key); KODOImageupload.Initialize(key);
}else if(key.getStorageType()==6){ }else if(key.getStorageType()==6){
ret = COSImageupload.Initialize(key); COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){ }else if(key.getStorageType()==7){
ret = FTPImageupload.Initialize(key); FtpServiceImpl.Initialize(key);
}else if(key.getStorageType()==8){ }else if(key.getStorageType()==8){
ret = UFileImageupload.Initialize(key); S3Imageupload.Initialize(key);
} }
} }
} }
@@ -1,11 +1,8 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.*;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.qiniu.common.QiniuException; import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone; import com.qiniu.common.Zone;
@@ -16,14 +13,11 @@ import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo; import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth; import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID;
@Service @Service
public class KODOImageupload { public class KODOImageupload {
@@ -31,9 +25,9 @@ public class KODOImageupload {
static BucketManager bucketManager; static BucketManager bucketManager;
static Keys key; static Keys key;
public ReturnImage ImageuploadKODO(Map<String, File> fileMap, String username, Integer keyID){ public ReturnImage ImageuploadKODO(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage(); ReturnImage returnImage = new ReturnImage();
Keys key = null;
Configuration cfg; Configuration cfg;
if (key.getEndpoint().equals("1")) { if (key.getEndpoint().equals("1")) {
cfg = new Configuration(Zone.zone0()); cfg = new Configuration(Zone.zone0());
@@ -48,21 +42,22 @@ public class KODOImageupload {
} }
UploadManager uploadManager = new UploadManager(cfg); UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(key.getAccessKey(), key.getAccessSecret()); Auth auth = Auth.create(key.getAccessKey(), key.getAccessSecret());
String upToken = auth.uploadToken(key.getBucketname(),null,7200,null); String upToken = auth.uploadToken(key.getBucketname(), null, 7200, null);
File file = null; File file = null;
try { try {
for (Map.Entry<String, File> entry : fileMap.entrySet()) { for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid(); String prefix = entry.getKey().get("prefix");
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); String ShortUIDName = entry.getKey().get("name");
file = entry.getValue(); file = entry.getValue();
try { try {
Response response = uploadManager.put(file,username + "/" + ShortUID + "." + entry.getKey(),upToken); Response response =
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); uploadManager.put(
returnImage.setImgname(username + "/" + ShortUID + "." + entry.getKey()); file, username + "/" + ShortUIDName + "." + prefix, upToken);
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + ShortUID + "." + entry.getKey()); DefaultPutRet putRet =
returnImage.setImgSize(entry.getValue().length()); new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
returnImage.setCode("200");
} catch (QiniuException ex) { } catch (QiniuException ex) {
returnImage.setCode("400");
Response r = ex.response; Response r = ex.response;
System.err.println(r.toString()); System.err.println(r.toString());
try { try {
@@ -71,65 +66,67 @@ public class KODOImageupload {
} }
} }
} }
}catch (Exception e){ returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
returnImage.setCode("500"); returnImage.setCode("500");
} }
return returnImage; return returnImage;
} }
//初始化
public static Integer Initialize(Keys k) { public static Integer Initialize(Keys k) {
int ret = -1; int ret = -1;
if (k.getEndpoint() != null && k.getAccessSecret() != null && k.getEndpoint() != null if (org.apache.commons.lang3.StringUtils.isBlank(k.getAccessKey())
&& k.getBucketname() != null && k.getRequestAddress() != null) { || org.apache.commons.lang3.StringUtils.isBlank(k.getAccessSecret())
if (!k.getEndpoint().equals("") && !k.getAccessSecret() .equals("") && !k.getEndpoint() .equals("") || org.apache.commons.lang3.StringUtils.isBlank(k.getEndpoint())
&& !k.getBucketname().equals("") && !k.getRequestAddress() .equals("")) { || org.apache.commons.lang3.StringUtils.isBlank(k.getBucketname())
Configuration cfg; || StringUtils.isBlank(k.getRequestAddress())) {
if (k.getEndpoint().equals("1")) { return -1;
cfg = new Configuration(Zone.zone0()); }
} else if (k.getEndpoint().equals("2")) { Configuration cfg;
cfg = new Configuration(Zone.zone1()); if (k.getEndpoint().equals("1")) {
} else if (k.getEndpoint().equals("3")) { cfg = new Configuration(Zone.zone0());
cfg = new Configuration(Zone.zone2()); } else if (k.getEndpoint().equals("2")) {
} else if (k.getEndpoint().equals("4")) { cfg = new Configuration(Zone.zone1());
cfg = new Configuration(Zone.zoneNa0()); } else if (k.getEndpoint().equals("3")) {
} else { cfg = new Configuration(Zone.zone2());
cfg = new Configuration(Zone.zoneAs0()); } else if (k.getEndpoint().equals("4")) {
} cfg = new Configuration(Zone.zoneNa0());
UploadManager uploadManager = new UploadManager(cfg); } else {
Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret()); cfg = new Configuration(Zone.zoneAs0());
String upToken = auth.uploadToken(k.getBucketname(),null,7200,null);//auth.uploadToken(k.getBucketname()); }
UploadManager uploadManager = new UploadManager(cfg);
BucketManager bucketManager = new BucketManager(auth, cfg); Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret());
BucketManager.FileListIterator fileListIterator = null; String upToken =
try { auth.uploadToken(
fileListIterator = bucketManager.createFileListIterator(k.getBucketname(), "", 1, "/"); k.getBucketname(),
FileInfo[] items = fileListIterator.next(); null,
if(items!=null){ 7200,
ret = 1; null); // auth.uploadToken(k.getBucketname());
bucketManager = bucketManager; BucketManager bmObj = new BucketManager(auth, cfg);
key = k; BucketManager.FileListIterator fileListIterator = null;
} try {
}catch (Exception e){ fileListIterator = bmObj.createFileListIterator(k.getBucketname(), "", 1, "/");
System.out.println("KODO Object Is null"); FileInfo[] items = fileListIterator.next();
ret = -1; if (items != null) {
} ret = 1;
bucketManager = bmObj;
key = k;
} }
} catch (Exception e) {
System.out.println("KODO Object Is null");
ret = -1;
} }
return ret; return ret;
} }
public Boolean delKODO(Integer keyID, String fileName) { public Boolean delKODO(Integer keyID, Images images) {
boolean b = true; boolean b = true;
try { try {
bucketManager.delete(key.getBucketname(), fileName); bucketManager.delete(key.getBucketname(), images.getImgname());
} catch (Exception ex) { } catch (Exception ex) {
b = false; b = false;
} }
return b; return b;
} }
} }
@@ -16,7 +16,6 @@ public class KeysServiceImpl implements KeysService {
@Autowired @Autowired
private KeysMapper keysMapper; private KeysMapper keysMapper;
@Autowired @Autowired
private NOSImageupload nOSImageupload; private NOSImageupload nOSImageupload;
@Autowired @Autowired
@@ -28,9 +27,9 @@ public class KeysServiceImpl implements KeysService {
@Autowired @Autowired
private COSImageupload cosImageupload; private COSImageupload cosImageupload;
@Autowired @Autowired
private FTPImageupload ftpImageupload; private FtpServiceImpl ftpService;
@Autowired @Autowired
private UFileImageupload uFileImageupload; private S3Imageupload s3Imageupload;
@Override @Override
@@ -52,9 +51,8 @@ public class KeysServiceImpl implements KeysService {
public Msg updateKey(Keys key) { public Msg updateKey(Keys key) {
Msg msg = new Msg(); Msg msg = new Msg();
Integer ret = -2; Integer ret = -2;
//修改完初始化
if(key.getStorageType()==1){ if(key.getStorageType()==1){
ret =nOSImageupload.Initialize(key);//实例化网易 ret =nOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){ }else if (key.getStorageType()==2){
ret = ossImageupload.Initialize(key); ret = ossImageupload.Initialize(key);
}else if(key.getStorageType()==3 ){ }else if(key.getStorageType()==3 ){
@@ -66,9 +64,9 @@ public class KeysServiceImpl implements KeysService {
}else if(key.getStorageType()==6){ }else if(key.getStorageType()==6){
ret = cosImageupload.Initialize(key); ret = cosImageupload.Initialize(key);
}else if(key.getStorageType()==7){ }else if(key.getStorageType()==7){
ret = ftpImageupload.Initialize(key); ret = ftpService.Initialize(key);
}else if(key.getStorageType()==8){ }else if(key.getStorageType()==8){
ret = uFileImageupload.Initialize(key); ret = s3Imageupload.Initialize(key);
}else{ }else{
Print.Normal("为获取到存储参数,或者使用存储源是本地的。"); Print.Normal("为获取到存储参数,或者使用存储源是本地的。");
} }
@@ -1,46 +1,37 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import java.io.File; import cn.hellohao.pojo.Images;
import java.io.FileInputStream; import cn.hellohao.pojo.Keys;
import java.util.*;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig; import cn.hellohao.utils.SetText;
import cn.hellohao.utils.*;
import com.netease.cloud.services.nos.model.NOSObjectSummary;
import com.netease.cloud.services.nos.model.ObjectListing;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.netease.cloud.auth.BasicCredentials; import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials; import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient; import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.Bucket; import com.netease.cloud.services.nos.model.ObjectListing;
import com.netease.cloud.services.nos.transfer.TransferManager; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import cn.hellohao.pojo.Keys; import java.io.File;
import java.util.Map;
@Service @Service
public class NOSImageupload { public class NOSImageupload {
static NosClient nosClient; static NosClient nosClient;
static Keys key; static Keys key;
public ReturnImage Imageupload(Map<String, File> fileMap, String username,Integer keyID){ public ReturnImage Imageupload(Map<Map<String, String>, File> fileMap, String username,Integer keyID){
ReturnImage returnImage = new ReturnImage(); ReturnImage returnImage = new ReturnImage();
File file = null; File file = null;
try { try {
for (Map.Entry<String, File> entry : fileMap.entrySet()) { for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid(); String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue(); file = entry.getValue();
nosClient.putObject(key.getBucketname(), username + "/" + ShortUID+ "." + entry.getKey(), file); nosClient.putObject(
returnImage.setImgname(username + "/" + ShortUID+ "." + entry.getKey()); key.getBucketname(), username + "/" + ShortUIDName + "." + prefix, file);
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + ShortUID + "." + entry.getKey());
returnImage.setImgSize(entry.getValue().length());
returnImage.setCode("200");
} }
}catch (Exception e){ returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
returnImage.setCode("500"); returnImage.setCode("500");
} }
@@ -49,42 +40,35 @@ public class NOSImageupload {
} }
//初始化网易NOS对象存储
public static Integer Initialize(Keys k) { public static Integer Initialize(Keys k) {
int ret = -1; int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null if (StringUtils.isBlank(k.getAccessKey())
&& k.getBucketname()!=null && k.getRequestAddress()!=null ){ || StringUtils.isBlank(k.getAccessSecret())
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") || StringUtils.isBlank(k.getEndpoint())
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ){ || StringUtils.isBlank(k.getBucketname())
// 初始化 || StringUtils.isBlank(k.getRequestAddress())) {
Credentials credentials = new BasicCredentials(k.getAccessKey(), k.getAccessSecret()); return -1;
NosClient nosClient = new NosClient(credentials); }
nosClient.setEndpoint(k.getEndpoint()); Credentials credentials = new BasicCredentials(k.getAccessKey(), k.getAccessSecret());
ObjectListing objectListing = null; NosClient nosObj = new NosClient(credentials);
try { nosObj.setEndpoint(k.getEndpoint());
objectListing = nosClient.listObjects(k.getBucketname()); ObjectListing objectListing = null;
ret = 1; try {
nosClient = nosClient; objectListing = nosObj.listObjects(k.getBucketname());
key = k; ret = 1;
}catch (Exception e){ nosClient = nosObj;
System.out.println("NOS Object Is null"); key = k;
ret = -1; }catch (Exception e){
} System.out.println("NOS Object Is null");
} ret = -1;
} }
//throw new StorageSourceInitException("当前数据源配置不完整,请管理员前往后台配置。");
return ret; return ret;
} }
public Boolean delNOS(Integer keyID, Images images) {
public Boolean delNOS(Integer keyID, String fileName) {
boolean b =true; boolean b =true;
try { try {
//这种方法不能删除指定文件夹下的文件 nosClient.deleteObject(key.getBucketname(), images.getImgname());
boolean isExist = nosClient.doesObjectExist(key.getBucketname(), fileName, null);
if (isExist) {
nosClient.deleteObject(key.getBucketname(), fileName);
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
b =false; b =false;
@@ -1,18 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.NoticeMapper;
import cn.hellohao.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class NoticeServiceImpl implements NoticeService {
@Autowired
private NoticeMapper noticeMapper;
@Override
public String getNotice() {
return noticeMapper.getNotice();
}
}
@@ -1,83 +1,89 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.utils.*; import cn.hellohao.utils.TypeDict;
import com.aliyun.oss.OSS; import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectListing; import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.util.*; import java.util.Map;
@Service @Service
public class OSSImageupload { public class OSSImageupload {
static OSSClient ossClient; static OSS ossClient;
static Keys key; static Keys key;
public ReturnImage ImageuploadOSS(Map<String, File> fileMap, String username,Integer keyID){ public ReturnImage ImageuploadOSS(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage(); ReturnImage returnImage = new ReturnImage();
File file = null; File file = null;
ObjectMetadata meta = new ObjectMetadata(); ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline"); meta.setHeader("Content-Disposition", "inline");
try { try {
for (Map.Entry<String, File> entry : fileMap.entrySet()) { for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid();//UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 String prefix = entry.getKey().get("prefix");
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); String ShortUIDName = entry.getKey().get("name");
// String times = format1.format(new Date());
file = entry.getValue(); file = entry.getValue();
System.out.println("待上传的图片:"+username + "/" + ShortUID + "." + entry.getKey()); Msg fileMiME = TypeDict.FileMiME(file);
ossClient.putObject(key.getBucketname(), username + "/" + ShortUID + "." + entry.getKey(),file); meta.setHeader("content-type", fileMiME.getData().toString());
returnImage.setImgname(username + "/" + ShortUID + "." + entry.getKey());//entry.getValue().getOriginalFilename() PutObjectRequest putObjectRequest =
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + ShortUID + "." + entry.getKey()); new PutObjectRequest(
returnImage.setImgSize(file.length()); key.getBucketname(),
returnImage.setCode("200"); username + "/" + ShortUIDName + "." + prefix,
file,
meta);
ossClient.putObject(putObjectRequest);
} }
}catch (Exception e){ returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
returnImage.setCode("500"); returnImage.setCode("500");
} }
return returnImage; return returnImage;
} }
//初始化
public static Integer Initialize(Keys k) { public static Integer Initialize(Keys k) {
int ret = -1; int ret = -1;
ObjectListing objectListing = null; ObjectListing objectListing = null;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getAccessKey()!=null && k.getEndpoint()!=null if (StringUtils.isBlank(k.getAccessKey())
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) { || StringUtils.isBlank(k.getAccessSecret())
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getAccessKey().equals("") && !k.getEndpoint().equals("") || StringUtils.isBlank(k.getEndpoint())
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) { || StringUtils.isBlank(k.getBucketname())
OSS ossClient = new OSSClientBuilder().build(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret()); || StringUtils.isBlank(k.getRequestAddress())) {
try { return -1;
objectListing = ossClient.listObjects(k.getBucketname());
ret=1;
ossClient = ossClient;
key = k;
} catch (Exception e) {
System.out.println("OSS Object Is null");
ret = -1;
}
}
} }
OSS ossObj =
new OSSClientBuilder()
.build(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret());
try {
objectListing = ossObj.listObjects(k.getBucketname());
ret = 1;
ossClient = ossObj;
key = k;
} catch (Exception e) {
System.out.println("OSS Object Is null");
ret = -1;
}
return ret; return ret;
} }
public boolean delOSS(Integer keyID, String fileName){ public boolean delOSS(Integer keyID, Images images) {
boolean b =true; boolean b = true;
try { try {
ossClient.deleteObject(key.getBucketname(), fileName); ossClient.deleteObject(key.getBucketname(), images.getImgname());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
b = false; b = false;
} }
return b; return b;
} }
} }
@@ -12,42 +12,44 @@ import java.util.concurrent.TimeUnit;
@Service @Service
public class RedisServiceImpl implements IRedisService { public class RedisServiceImpl implements IRedisService {
@Autowired @Autowired private StringRedisTemplate stringRedisTemplate;
private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Override
public void setValue(String key, Map<String, Object> value) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue();
vo.set(key, value);
redisTemplate.expire(key, 1, TimeUnit.HOURS); // 这里指的是1小时后失效
}
@Override @Override
public void setValue(String key, Map<String, Object> value) { public Object getValue(String key) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue(); ValueOperations<String, String> vo = redisTemplate.opsForValue();
vo.set(key, value); return vo.get(key);
redisTemplate.expire(key, 1, TimeUnit.HOURS); // 这里指的是1小时后失效 }
}
@Override @Override
public Object getValue(String key) { public void setValue(String key, String value) {
ValueOperations<String, String> vo = redisTemplate.opsForValue(); ValueOperations<String, Object> vo = redisTemplate.opsForValue();
return vo.get(key); vo.set(key, value);
} redisTemplate.expire(key, 3, TimeUnit.MINUTES); // 这里指的是1小时后失效 时HOURS 分 MINUTES
}
@Override @Override
public void setValue(String key, String value) { public void setTimeValue(String key, Object value, Long time) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue(); ValueOperations<String, Object> vo = redisTemplate.opsForValue();
vo.set(key, value); vo.set(key, value);
redisTemplate.expire(key, 3, TimeUnit.MINUTES); // 这里指的是1小时后失效 时HOURS 分 MINUTES redisTemplate.expire(key, time, TimeUnit.HOURS);
} }
@Override @Override
public void setValue(String key, Object value) { public Object getMapValue(String key) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue(); ValueOperations<String, String> vo = redisTemplate.opsForValue();
vo.set(key, value); return vo.get(key);
redisTemplate.expire(key, 1, TimeUnit.HOURS); // 这里指的是1小时后失效 }
}
@Override @Override
public Object getMapValue(String key) { public Boolean removeValue(String key) {
ValueOperations<String, String> vo = redisTemplate.opsForValue(); return redisTemplate.delete(key);
return vo.get(key); }
} }
}
@@ -0,0 +1,167 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
import java.util.Map;
/**
* @author Hellohao
* @version 1.0
* @date 2023/3/15 14:04
*/
@Service
public class S3Imageupload {
private static Logger logger = LoggerFactory.getLogger(S3Imageupload.class);
static AmazonS3 AS3;
static Keys KEY;
public ReturnImage ImageuploadS3(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage();
try {
if (null == AS3 || null == AS3) {
logger.error("S3 = 存储源对象为空");
returnImage.setCode("500");
return returnImage;
}
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
return returnImage;
}
File file = null;
try {
for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue();
AS3.putObject(
new PutObjectRequest(
KEY.getBucketname(),
username + "/" + ShortUIDName + "." + prefix,
file));
// S3Object object = s3.getObject( new GetObjectRequest( key.getBucketname(),
}
returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace();
returnImage.setCode("500");
}
return returnImage;
}
public static Integer Initialize(Keys k) {
int ret = -1;
if (StringUtils.isBlank(k.getAccessKey())
|| StringUtils.isBlank(k.getAccessSecret())
|| StringUtils.isBlank(k.getRootPath())
|| StringUtils.isBlank(k.getEndpoint())
|| StringUtils.isBlank(k.getBucketname())
|| StringUtils.isBlank(k.getRequestAddress())) {
return -1;
}
try {
String regionStr = k.getRegion() == null ? "" : k.getRegion();
ClientConfiguration config = new ClientConfiguration();
config.setMaxConnections(500);
config.setConnectionTimeout(30);
// cn-north-1 us-east-1
BasicAWSCredentials credentials =
new BasicAWSCredentials(k.getAccessKey(), k.getAccessSecret());
AmazonS3 s3 =
AmazonS3ClientBuilder.standard()
.withClientConfiguration(config)
.withPathStyleAccessEnabled(false)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(
k.getEndpoint(), regionStr))
.build();
ObjectListing objectListing = s3.listObjects(k.getBucketname());
ret = 1;
AS3 = s3;
KEY = k;
} catch (Exception e) {
logger.warn("S3 Object " + k.getKeyname() + " Is null");
ret = -1;
}
if(ret==-1){
ret = Initialize_Tow(k);
if(ret>-1){
//OK
}
}
return ret;
}
public static Integer Initialize_Tow(Keys k) {
int ret = -1;
try {
ClientConfiguration config = new ClientConfiguration();
AwsClientBuilder.EndpointConfiguration endpointConfig =
new AwsClientBuilder.EndpointConfiguration(k.getEndpoint(), k.getRegion());//cn-north-1
AWSCredentials awsCredentials = new BasicAWSCredentials(k.getAccessKey(),k.getAccessSecret());
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
AmazonS3 s3 = AmazonS3Client.builder()
.withEndpointConfiguration(endpointConfig)
.withClientConfiguration(config)
.withCredentials(awsCredentialsProvider)
.disableChunkedEncoding()
.withPathStyleAccessEnabled(true)
.build();
List<Bucket> buckets = s3.listBuckets();
boolean b = false;
for (Bucket bucket : buckets) {
if(k.getBucketname().equals(bucket.getName())){
b = true;
}
}
if(b==false){
throw new NullPointerException();
}
ret=1;
AS3 = s3;
KEY = k;
} catch (Exception e) {
ret = -1;
}
return ret;
}
public boolean deleS3(Integer keyID, Images images) {
boolean b = true;
try {
DeleteObjectRequest deleteObjectRequest =
new DeleteObjectRequest(KEY.getBucketname(), images.getImgname());
AS3.deleteObject(deleteObjectRequest);
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -1,83 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.*;
import com.UpYun;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.*;
@Service
public class UFileImageupload {
static UpYun uFile;
static Keys key;
public ReturnImage ImageuploadUFile(Map<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<String, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid();
file = entry.getValue();
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{
System.err.println("上传失败");
}
}
}catch(Exception e){
returnImage.setCode("500");
}
return returnImage;
}
//ufile初始化
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实例。
UpYun uFile = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret());
List<UpYun.FolderItem> items = null;
try {
items = uFile.readDir("/",null);
ret = 1;
uFile = uFile;
key = k;
} catch (Exception e) {
System.out.println("UFile Object Is null");
ret = -1;
}
}
}
return ret;
}
public Boolean delUFile(Integer keyID, String fileName) {
boolean b = true;
try {
boolean result = uFile.deleteFile(fileName, null);
} catch (Exception e) {
e.printStackTrace();
b = false;
}
return b;
}
}
@@ -0,0 +1,102 @@
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;
}
}
@@ -1,88 +1,89 @@
package cn.hellohao.service.impl; package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig; import cn.hellohao.utils.TypeDict;
import cn.hellohao.utils.*;
import com.UpYun; import com.UpYun;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.ObjectMetadata;
import com.upyun.UpException; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.io.IOException; import java.util.List;
import java.util.*; import java.util.Map;
@Service @Service
public class USSImageupload { public class USSImageupload {
static UpYun upyun; static UpYun upyun;
static Keys key; static Keys key;
public ReturnImage ImageuploadUSS(Map<String, File> fileMap, String username,Integer keyID) { public ReturnImage ImageuploadUSS(
Map<Map<String, String>, File> fileMap, String username, Integer keyID) {
ReturnImage returnImage = new ReturnImage(); ReturnImage returnImage = new ReturnImage();
File file = null; File file = null;
ObjectMetadata meta = new ObjectMetadata(); ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline"); meta.setHeader("Content-Disposition", "inline");
try { try {
for (Map.Entry<String, File> entry : fileMap.entrySet()) { for (Map.Entry<Map<String, String>, File> entry : fileMap.entrySet()) {
String ShortUID = SetText.getShortUuid(); String prefix = entry.getKey().get("prefix");
String ShortUIDName = entry.getKey().get("name");
file = entry.getValue(); file = entry.getValue();
Msg fileMiME = TypeDict.FileMiME(file);
meta.setHeader("content-type", fileMiME.getData().toString());
upyun.setContentMD5(UpYun.md5(file)); upyun.setContentMD5(UpYun.md5(file));
boolean result = upyun.writeFile(username + "/" + ShortUID + "." + entry.getKey(), file, true); boolean result =
if(result){ upyun.writeFile(username + "/" + ShortUIDName + "." + prefix, file, true);
returnImage.setImgname(username + "/" + ShortUID + "." + entry.getKey()); if (result) {
returnImage.setImgurl(key.getRequestAddress() + "/" +username + "/" + ShortUID + "." + entry.getKey());
returnImage.setImgSize(entry.getValue().length()); } else {
returnImage.setCode("200");
}else{
System.err.println("上传失败"); System.err.println("上传失败");
returnImage.setCode("400");
} }
} }
}catch (Exception e){ returnImage.setCode("200");
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
returnImage.setCode("500"); returnImage.setCode("500");
} }
return returnImage; return returnImage;
} }
//初始化 // 初始化
public static Integer Initialize(Keys k) { public static Integer Initialize(Keys k) {
int ret = -1; int ret = -1;
if(k.getStorageType()!=null && k.getAccessKey() != null && k.getAccessSecret() != null && k.getBucketname() != null if (StringUtils.isBlank(k.getAccessKey())
&& k.getRequestAddress() !=null ) { || StringUtils.isBlank(k.getKeyname())
if(!k.getStorageType().equals("") && !k.getAccessKey().equals("") && !k.getAccessSecret().equals("") && !k.getBucketname().equals("") || StringUtils.isBlank(k.getAccessSecret())
&& !k.getRequestAddress().equals("") ) { || StringUtils.isBlank(k.getEndpoint())
// 初始化 || StringUtils.isBlank(k.getBucketname())
// 创建UpYun实例。 || StringUtils.isBlank(k.getRequestAddress())
UpYun upyun = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret()); || k.getStorageType() == null) {
List<UpYun.FolderItem> items = null; return -1;
try { }
items = upyun.readDir("/",null); UpYun upObj = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret());
ret = 1; List<UpYun.FolderItem> items = null;
upyun = upyun; try {
key = k; items = upObj.readDir("/", null);
} catch (Exception e) { ret = 1;
System.out.println("USS Object Is null"); upyun = upObj;
ret = -1; key = k;
} } catch (Exception e) {
} System.out.println("USS Object Is null");
ret = -1;
} }
return ret; return ret;
} }
public Boolean delUSS(Integer keyID, String fileName) { public Boolean delUSS(Integer keyID, Images images) {
boolean b = true; boolean b = true;
try { try {
boolean result = upyun.deleteFile(fileName, null); boolean result = upyun.deleteFile(images.getImgname(), null);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
b=false; b = false;
} }
return b; return b;
} }
} }
@@ -3,24 +3,20 @@ package cn.hellohao.service.impl;
import cn.hellohao.dao.*; import cn.hellohao.dao.*;
import cn.hellohao.pojo.*; import cn.hellohao.pojo.*;
import cn.hellohao.service.ImgTempService; import cn.hellohao.service.ImgTempService;
import cn.hellohao.service.SysConfigService;
import cn.hellohao.utils.*; import cn.hellohao.utils.*;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.*; import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
@@ -29,76 +25,68 @@ import java.util.*;
* @version 1.0 * @version 1.0
* @date 2020/1/9 15:46 * @date 2020/1/9 15:46
*/ */
@Service @Service
public class UploadServicel { public class UploadServicel {
@Autowired
ConfigMapper configMapper;
@Autowired
SysConfigService sysConfigService;
@Autowired
UploadConfigMapper uploadConfigMapper;
@Autowired
KeysMapper keysMapper;
@Autowired
ImgMapper imgMapper;
@Autowired
UserMapper userMapper;
@Autowired
ImgreviewMapper imgreviewMapper;
@Autowired
ImgTempService imgTempService;
private static Logger logger = LoggerFactory.getLogger(UploadServicel.class);
@Autowired private UploadConfigMapper uploadConfigMapper;
@Autowired private KeysMapper keysMapper;
@Autowired private ImgMapper imgMapper;
@Autowired private UserMapper userMapper;
@Autowired private ImgTempService imgTempService;
@Autowired private GetSource getSource;
@Autowired deleImages deleimages;
@Autowired ImgViolationJudgeServiceImpl imgViolationJudgeService;
public Msg uploadForLoc(
public Msg uploadForLoc(HttpServletRequest request, HttpServletRequest request,
MultipartFile multipartFile, Integer setday, String imgUrl, JSONArray selectTreeList) { MultipartFile multipartFile,
Integer setday,
String imgUrl) {
Msg msg = new Msg(); Msg msg = new Msg();
try{ try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String imageFileName = "未命名图像";
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig(); UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig();
String userip = GetIPS.getIpAddr(request); String userip = GetIPS.getIpAddr(request);
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
User u = (User) subject.getPrincipal(); User u = (User) subject.getPrincipal();
if(null!=u){ if (null != u) {
u = userMapper.getUsers(u); u = userMapper.getUsers(u);
} }
Integer sourceKeyId = 0; Integer sourceKeyId = 0;
String md5key = null; String md5key = null;
FileInputStream fis = null; FileInputStream fis = null;
File file =null; File file = null;
if(imgUrl==null){ if (imgUrl == null) {
imageFileName = multipartFile.getOriginalFilename();
file = SetFiles.changeFile_new(multipartFile); file = SetFiles.changeFile_new(multipartFile);
}else{ } else {
//说明是URL上传 imageFileName = "URL转存图像";
Msg imgData = uploadForURL(request, imgUrl); Msg imgData = uploadForURL(request, imgUrl);
if(imgData.getCode().equals("200")){ if (imgData.getCode().equals("200")) {
file = new File((String) imgData.getData()); file = new File((String) imgData.getData());
}else{ } else {
return imgData; return imgData;
} }
} }
String imguid = UUID.randomUUID().toString().replace("-", ""); String imguid = UUID.randomUUID().toString().replace("-", "");
//判断上传前的一些用户限制信息 Msg msg1 = updateImgCheck(u, uploadConfig);
Msg msg1 = updateImgCheck(u,uploadConfig); if (!msg1.getCode().equals("300")) {
if(!msg1.getCode().equals("300")){
return msg1; return msg1;
} }
//判断可用容量
sourceKeyId = group.getKeyid(); sourceKeyId = group.getKeyid();
Keys key = keysMapper.selectKeys(sourceKeyId); Keys key = keysMapper.selectKeys(sourceKeyId);
Long tmp = (memory == -1 ? -2 : UsedTotleMemory); Long tmp = (memory == -1 ? -2 : UsedTotleMemory);
if (tmp >= memory) { if (tmp >= memory) {
msg.setCode("4005"); msg.setCode("4005");
msg.setInfo(u==null?"游客空间已用尽":"您的可用空间不足"); msg.setInfo(u == null ? "游客空间已用尽" : "您的可用空间不足");
return msg; return msg;
} }
//判断图片有没有超出设定大小
if (file.length() > TotleMemory) { if (file.length() > TotleMemory) {
System.err.println("文件大小:"+file.length()); System.err.println("文件大小:" + file.length());
System.err.println("最大限制:"+TotleMemory); System.err.println("最大限制:" + TotleMemory);
msg.setCode("4006"); msg.setCode("4006");
msg.setInfo("图像超出系统限制大小"); msg.setInfo("图像超出系统限制大小");
return msg; return msg;
@@ -110,36 +98,17 @@ public class UploadServicel {
e.printStackTrace(); e.printStackTrace();
System.out.println("未获取到图片的MD5,成成UUID"); System.out.println("未获取到图片的MD5,成成UUID");
} }
Msg fileMiME = TypeDict.FileMiME(file, uploadConfig.getSuffix()); Msg fileMiME = TypeDict.FileMiME(file);
if(!fileMiME.getCode().equals("200")) { if (!fileMiME.getCode().equals("200")) {
//非图像文本
msg.setCode("4000"); msg.setCode("4000");
msg.setInfo(fileMiME.getInfo()); msg.setInfo(fileMiME.getInfo());
return msg; return msg;
} }
if(md5key==null || md5key.equals("")){ if (md5key == null || md5key.equals("")) {
md5key = UUID.randomUUID().toString().replace("-", ""); md5key = UUID.randomUUID().toString().replace("-", "");
} }
String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
//判断图片是否存在 // 判断黑名单
if(Integer.valueOf(sysConfigService.getstate().getCheckduplicate())==1){
Images imaOBJ = new Images();
imaOBJ.setMd5key(md5key);
imaOBJ.setUserid(u==null?0:u.getId());
if(imgMapper.md5Count(imaOBJ)>0){
Images images = imgMapper.selectImgUrlByMD5(md5key);
jsonObject.put("url", images.getImgurl());
jsonObject.put("name",file.getName());
jsonObject.put("imguid",images.getImguid());
// jsonObject.put("shortLink",images.getShortlink());
msg.setData(jsonObject);
return msg;
}
}
String prefix = file.getName().substring(file.getName().lastIndexOf(".")+1);
//判断黑名单
if (uploadConfig.getBlacklist() != null) { if (uploadConfig.getBlacklist() != null) {
String[] iparr = uploadConfig.getBlacklist().split(";"); String[] iparr = uploadConfig.getBlacklist().split(";");
for (String s : iparr) { for (String s : iparr) {
@@ -151,52 +120,90 @@ public class UploadServicel {
} }
} }
} }
// 先存数据库
Map<String, File> map = new HashMap<>(); Images imgObj = new Images();
String imgnameEd = null;
Map<Map<String, String>, File> map = new HashMap<>();
if (file.exists()) { if (file.exists()) {
map.put(prefix, file);//prefix 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(key.getRequestAddress() + "/" + imgnameEd);
}
imgObj.setSizes(Long.toString(file.length()));
}else{
msg.setInfo("未获取到指定图像:110503");
msg.setCode("110503");
return msg;
}
imgObj.setUpdatetime(df.format(new Date()));
imgObj.setSource(key.getId());
imgObj.setUserid(u == null ? 0 : u.getId());
if (setday == 1 || setday == 3 || setday == 7 || setday == 30) {
imgObj.setImgtype(1);
ImgTemp imgDataExp = new ImgTemp();
imgDataExp.setDeltime(plusDay(setday));
imgDataExp.setImguid(imguid);
imgTempService.insertImgExp(imgDataExp);
} else {
imgObj.setImgtype(0);
}
imgObj.setAbnormal(userip);
imgObj.setMd5key(md5key);
imgObj.setImguid(imguid);
imgObj.setFormat(fileMiME.getData().toString());
imgObj.setIdname(imageFileName);
Integer insertRet = imgMapper.insertImgData(imgObj);
if (insertRet == 0) {
Images imaOBJ = new Images();
imaOBJ.setMd5key(md5key);
imaOBJ.setUserid(u == null ? 0 : u.getId());
List<Images> images = imgMapper.selectImgUrlByMD5(md5key);
if (images.size() > 0) {
jsonObject.put("url", images.get(0).getImgurl());
// Keys imgFromKey = keysService.selectKeys(images.get(0).getSource());
// if (imgFromKey.getStorageType().equals(5)) {
// jsonObject.put(
// "url",
// imgFromKey.getRequestAddress()
// + "/ota/"
// + images.get(0).getImgname());
// } else {
// jsonObject.put("url", images.get(0).getImgurl());
// }
jsonObject.put("name", file.getName());
jsonObject.put("imguid", images.get(0).getImguid());
msg.setData(jsonObject);
return msg;
} else {
msg.setInfo("未获取到指定图像");
msg.setCode("110501");
return msg;
}
} }
long stime = System.currentTimeMillis(); long stime = System.currentTimeMillis();
Map<ReturnImage, Integer> m = null; ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId());
ReturnImage returnImage = GetSource.storageSource(key.getStorageType(), map, updatePath, key.getId()); if (returnImage.getCode().equals("200")) {
Images img = new Images();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(returnImage.getCode().equals("200")){
String imgurl = returnImage.getImgurl();
Long imgsize = returnImage.getImgSize();
String imgname = returnImage.getImgname();
img.setImgurl(imgurl);
img.setUpdatetime(df.format(new Date()));
img.setSource(key.getId());
img.setUserid(u == null ? 0 : u.getId());
img.setSizes(imgsize.toString());
if(uploadConfig.getUrltype()==2){
img.setImgname(imgname);
}else{
img.setImgname(SetText.getSubString(imgname, key.getRequestAddress() + "/", ""));
}
if(setday == 1 || setday == 3 || setday == 7 || setday == 30){
img.setImgtype(1);
ImgTemp imgDataExp = new ImgTemp();
imgDataExp.setDeltime(plusDay(setday));
imgDataExp.setImguid(imguid);
imgTempService.insertImgExp(imgDataExp);
}else{
img.setImgtype(0);
}
img.setAbnormal(userip);
img.setMd5key(md5key);
img.setImguid(imguid);
img.setFormat(fileMiME.getData().toString());
userMapper.insertimg(img);
long etime = System.currentTimeMillis(); long etime = System.currentTimeMillis();
Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms"); Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms");
jsonObject.put("url", img.getImgurl()); jsonObject.put("url", imgObj.getImgurl());
jsonObject.put("name", imgname); jsonObject.put("name", imgObj.getImgname());
jsonObject.put("imguid",img.getImguid()); jsonObject.put("imguid", imgObj.getImguid());
// jsonObject.put("shortLink", img.getShortlink()); imgViolationJudgeService.LegalImageCheck(imgObj,key);
new Thread(()->{LegalImageCheck(img);}).start(); // new Thread(
}else{ // () -> {
// LegalImageCheck(imgObj);
// })
// .start();
} else {
imgMapper.deleimgForImgUid(imgObj.getImguid());
msg.setCode("5001"); msg.setCode("5001");
msg.setInfo("上传服务内部错误"); msg.setInfo("上传服务内部错误");
return msg; return msg;
@@ -204,94 +211,95 @@ public class UploadServicel {
file.delete(); file.delete();
msg.setData(jsonObject); msg.setData(jsonObject);
return msg; return msg;
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
msg.setInfo("上传时发生了一些错误"); msg.setInfo("上传时发生了一些错误");
msg.setCode("110500"); msg.setCode("110500");
return msg; return msg;
} }
} }
public static Msg uploadForURL(HttpServletRequest request, String imgurl) {
//通过图片Url上传图片 Msg msg = new Msg();
public static Msg uploadForURL(HttpServletRequest request, String imgurl){ if (true) {
final Msg msg = new Msg(); Long imgsize = 0L;
//先判断是不是有效链接
// final boolean valid = ImgUrlUtil.isValid(imgurl);
if(true){
Long imgsize = null;
try { try {
imgsize = ImgUrlUtil.getFileLength(imgurl); if (imgsize == 0) {
if(imgsize>0){
// String uuid= UUID.randomUUID().toString().replace("-", "");
String ShortUID = SetText.getShortUuid(); String ShortUID = SetText.getShortUuid();
String savePath = request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator; String savePath =
Map<String ,Object> bl =ImgUrlUtil.downLoadFromUrl (imgurl, ShortUID, savePath); request.getSession().getServletContext().getRealPath("/")
if((Boolean) bl.get("res")==true){ + File.separator
// File file = new File(); + "hellohaotmp"
+ File.separator;
Map<String, Object> bl = ImgUrlUtil.downLoadFromUrl(imgurl, ShortUID, savePath);
if ((Boolean) bl.get("res") == true) {
msg.setCode("200"); msg.setCode("200");
msg.setData(bl.get("imgPath"));//savePath + File.separator + ShortUID msg.setData(bl.get("imgPath"));
return msg; return msg;
}else{ } else {
if(bl.get("StatusCode").equals("110403")){ if (bl.get("StatusCode").equals("110403")) {
msg.setInfo("该链接非图像文件,无法上传"); msg.setInfo("该链接非图像文件,无法上传");
}else{ } else {
msg.setInfo("该链接暂时无法上传"); msg.setInfo("该链接暂时无法上传");
} }
msg.setCode("500"); msg.setCode("500");
} }
}else{ } else {
msg.setCode("500"); msg.setCode("500");
msg.setInfo("获取资源失败"); msg.setInfo("获取资源失败");
} }
} catch (IOException e) { } catch (Exception e) {
msg.setCode("500"); msg.setCode("500");
msg.setInfo("获取资源失败"); msg.setInfo("获取资源失败");
} }
}else{ } else {
msg.setCode("500"); msg.setCode("500");
msg.setInfo("该链接无效"); msg.setInfo("该链接无效");
} }
return msg; 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";
public static Group group; //上传用户或游客的所属分组 // 判断用户 或 游客 当前上传图片的一系列校验
public static Long memory;//上传用户或者游客的分配容量 memory private Msg updateImgCheck(User user, UploadConfig uploadConfig) {
public static Long TotleMemory;//用户或者游客下可使用的总容量 //maxsize Msg msg = new Msg();
public static Long UsedTotleMemory;//用户或者游客已经用掉的总容量 //usermemory
public static String updatePath="tourist";
//判断用户 或 游客 当前上传图片的一系列校验
private Msg updateImgCheck(User user, UploadConfig uploadConfig){
final Msg msg = new Msg();
java.text.DateFormat dateFormat = null; java.text.DateFormat dateFormat = null;
try { try {
dateFormat = new SimpleDateFormat("yyyy/MM/dd"); dateFormat = new SimpleDateFormat("yyyy/MM/dd");
if (user == null) { if (user == null) {
//用户没有登陆,值判断游客能不能上传即可 if (uploadConfig.getIsupdate() != 1) {
if(uploadConfig.getIsupdate()!=1){
msg.setCode("1000"); msg.setCode("1000");
msg.setInfo("系统已禁用游客上传"); msg.setInfo("系统已禁用游客上传");
return msg; return msg;
} }
updatePath = "tourist";
group = GetCurrentSource.GetSource(null); group = GetCurrentSource.GetSource(null);
memory = Long.valueOf(uploadConfig.getVisitormemory());//单位 B 游客设置总量 memory = Long.valueOf(uploadConfig.getVisitormemory()); // 单位 B 游客设置总量
TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists());//单位 B 游客单文件大小 TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists()); // 单位 B 游客单文件大小
UsedTotleMemory = imgMapper.getusermemory(0)==null?0L : imgMapper.getusermemory(0);//单位 B UsedTotleMemory =
imgMapper.getusermemory(0) == null
? 0L
: imgMapper.getusermemory(0); // 单位 B
} else { } else {
//判断用户能不能上传 if (uploadConfig.getUserclose() != 1) {
if(uploadConfig.getUserclose()!=1){
msg.setCode("1001"); msg.setCode("1001");
msg.setInfo("系统已禁用上传功能"); msg.setInfo("系统已禁用上传功能");
return msg; return msg;
} }
updatePath = user.getUsername(); updatePath = user.getUsername();
group= GetCurrentSource.GetSource(user.getId()); group = GetCurrentSource.GetSource(user.getId());
memory = Long.valueOf(user.getMemory())*1024*1024;//单位 B memory = Long.valueOf(user.getMemory()); // 单位 B *1024*1024
TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser());//单位 B TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser()); // 单位 B
UsedTotleMemory = imgMapper.getusermemory(user.getId())==null?0L:imgMapper.getusermemory(user.getId());//单位 B UsedTotleMemory =
imgMapper.getusermemory(user.getId()) == null
? 0L
: imgMapper.getusermemory(user.getId()); // 单位 B
} }
if (uploadConfig.getUrltype() == 2) { if (uploadConfig.getUrltype() == 2) {
updatePath = dateFormat.format(new Date()); updatePath = dateFormat.format(new Date());
@@ -304,82 +312,19 @@ public class UploadServicel {
return msg; return msg;
} }
private synchronized void LegalImageCheck(Images images){
System.out.println("非法图像鉴别进程启动");
Imgreview imgreview = null;
try {
imgreview = imgreviewMapper.selectByusing(1);
} catch (Exception e) {
Print.warning("获取鉴别程序的时候发生错误");
e.printStackTrace();
}
if(null != imgreview){
LegalImageCheckForBaiDu(imgreview,images);
}
} // 计算时间
public static String plusDay(int setday) {
private void LegalImageCheckForBaiDu(Imgreview imgreview,Images images){
System.out.println("非法图像鉴别进程启动-BaiDu");
if(imgreview.getUsing()==1){
try {
AipContentCensor client = new AipContentCensor(imgreview.getAppId(), imgreview.getApiKey(), imgreview.getSecretKey());
client.setConnectionTimeoutInMillis(5000);
client.setSocketTimeoutInMillis(30000);
org.json.JSONObject res = client.antiPorn(images.getImgurl());
res = client.imageCensorUserDefined(images.getImgurl(), EImgType.URL, null);
System.err.println("返回的鉴黄json:"+res.toString());
com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray("[" + res.toString() + "]");
for (Object o : jsonArray) {
com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) o;
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
Integer conclusionType = jsonObject.getInteger("conclusionType");
if(conclusionType!=null){
if (conclusionType == 2) {
for (Object datum : data) {
com.alibaba.fastjson.JSONObject imgdata = (com.alibaba.fastjson.JSONObject) datum;
if (imgdata.getInteger("type") == 1) {
Images img = new Images();
img.setImgname(images.getImgname());
img.setViolation("1[1]");
imgMapper.setImg(img);
Imgreview imgv = new Imgreview();
imgv.setId(1);
Integer count = imgreview.getCount();
System.out.println("违法图片总数:" + count);
imgv.setCount(count + 1);
imgreviewMapper.updateByPrimaryKeySelective(imgv);
System.err.println("存在非法图片,进行处理操作");
}
}
}
}
}
}catch (Exception e){
System.out.println("图像鉴黄线程执行过程中出现异常");
e.printStackTrace();
}
}
}
//计算时间
public static String plusDay(int setday){
Date d = new Date(); Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currdate = format.format(d); String currdate = format.format(d);
System.out.println("现在的日期是:" + currdate); System.out.println("现在的日期是:" + currdate);
Calendar ca = Calendar.getInstance(); Calendar ca = Calendar.getInstance();
ca.setTime(d); ca.setTime(d);
ca.add(Calendar.DATE, setday);// num为增加的天数,可以改变的 ca.add(Calendar.DATE, setday); // num为增加的天数,可以改变的
d = ca.getTime(); d = ca.getTime();
String enddate = format.format(d); String enddate = format.format(d);
System.out.println("到期的日期:" + enddate); System.out.println("到期的日期:" + enddate);
return enddate; return enddate;
} }
} }
@@ -3,7 +3,6 @@ package cn.hellohao.service.impl;
import cn.hellohao.dao.CodeMapper; import cn.hellohao.dao.CodeMapper;
import cn.hellohao.dao.UserMapper; import cn.hellohao.dao.UserMapper;
import cn.hellohao.exception.CodeException; import cn.hellohao.exception.CodeException;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User; import cn.hellohao.pojo.User;
import cn.hellohao.service.UserService; import cn.hellohao.service.UserService;
import cn.hellohao.utils.Print; import cn.hellohao.utils.Print;
@@ -31,17 +30,17 @@ public class UserServiceImpl implements UserService {
return userMapper.login(email, password,uid); return userMapper.login(email, password,uid);
} }
@Override
public User loginByToken(String token) {
return userMapper.loginByToken(token);
}
@Override @Override
public User getUsers(User user) { public User getUsers(User user) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return userMapper.getUsers(user); return userMapper.getUsers(user);
} }
@Override
public Integer insertimg(Images img) {
// TODO Auto-generated method stub
return userMapper.insertimg(img);
}
@Override @Override
public Integer change(User user) { public Integer change(User user) {
@@ -0,0 +1,160 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.Msg;
import cn.hellohao.service.IRedisService;
import cn.hellohao.service.ImgAndAlbumService;
import cn.hellohao.service.ImgService;
import cn.hellohao.service.ImgTempService;
import cn.hellohao.utils.LocUpdateImg;
import cn.hellohao.utils.progress.MyProgress;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class deleImages {
@Autowired private NOSImageupload nosImageupload;
@Autowired private OSSImageupload ossImageupload;
@Autowired private COSImageupload cosImageupload;
@Autowired private KODOImageupload kodoImageupload;
@Autowired private USSImageupload ussImageupload;
@Autowired private S3Imageupload s3Imageupload;
@Autowired private FtpServiceImpl ftpService;
@Autowired private ImgAndAlbumService imgAndAlbumService;
@Autowired private ImgTempService imgTempService;
@Autowired private ImgService imgService;
@Autowired private KeysServiceImpl keysService;
@Autowired private IRedisService iRedisService;
public Msg dele(String uuid, Long... imgIds) {
Msg msg = new Msg();
MyProgress myProgress = new MyProgress();
myProgress.InitializeDelImg();
List<Long> ids = new ArrayList<>();
int successCount = 0;
List<String> errorIds = new ArrayList<>();
for (int i = 0; i < imgIds.length; i++) {
// 删除图片
boolean isDele = false;
try {
Images image = imgService.selectByPrimaryKey(imgIds[i]);
Keys key = keysService.selectKeys(image.getSource());
if (key.getStorageType() == 1) {
isDele = nosImageupload.delNOS(key.getId(), image);
} else if (key.getStorageType() == 2) {
isDele = ossImageupload.delOSS(key.getId(), image);
} else if (key.getStorageType() == 3) {
isDele = ussImageupload.delUSS(key.getId(), image);
} else if (key.getStorageType() == 4) {
isDele = kodoImageupload.delKODO(key.getId(), image);
} else if (key.getStorageType() == 5) {
isDele = LocUpdateImg.deleteLOCImg(image);
} else if (key.getStorageType() == 6) {
isDele = cosImageupload.delCOS(key.getId(), image);
} else if (key.getStorageType() == 7) {
isDele = ftpService.delFTP(key.getId(), image);
} else if (key.getStorageType() == 8) {
isDele = s3Imageupload.deleS3(key.getId(), image);
} else {
System.err.println("未获取到对象存储参数,删除失败。");
}
// if (isDele) {
try {
imgAndAlbumService.deleteImgAndAlbum(image.getImgurl());
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
ids.add(image.getId());
successCount++;
System.out.println("删除成功加一个" + image.getId());
} catch (Exception e) {
e.printStackTrace();
System.err.println(image.getImgname() + ":图片数据库记录时发生错误");
errorIds.add(image.getImgurl());
}
// }
if(uuid!=null){
myProgress.setDelSuccessCount(successCount);
myProgress.setDelSuccessImgList(ids);
myProgress.setDelErrorImgListt(errorIds);
if (imgIds.length == (i + 1)) {
myProgress.setDelOCT(1);
} else {
myProgress.setDelOCT(0);
}
iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L);
}
} catch (Exception e) {
System.err.println("删除的时候发生了一些异常");
ids.add(imgIds[i]);
successCount++;
if(uuid!=null){
myProgress.setDelSuccessCount(successCount);
myProgress.setDelSuccessImgList(ids);
myProgress.setDelErrorImgListt(errorIds);
if (imgIds.length == (i + 1)) {
myProgress.setDelOCT(1);
} else {
myProgress.setDelOCT(0);
}
iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L);
}
e.printStackTrace();
}
}
msg.setData(ids);
return msg;
}
public Msg dele2(String... imgIds) {
Msg msg = new Msg();
List<Long> ids = new ArrayList<>();
for (int i = 0; i < imgIds.length; i++) {
try {
Images image = imgService.selectByPrimaryKey(Long.valueOf(imgIds[i]));
Keys key = keysService.selectKeys(image.getSource());
if (key.getStorageType() == 1) {
nosImageupload.delNOS(key.getId(), image);
} else if (key.getStorageType() == 2) {
ossImageupload.delOSS(key.getId(), image);
} else if (key.getStorageType() == 3) {
ussImageupload.delUSS(key.getId(), image);
} else if (key.getStorageType() == 4) {
kodoImageupload.delKODO(key.getId(), image);
} else if (key.getStorageType() == 5) {
LocUpdateImg.deleteLOCImg(image);
} else if (key.getStorageType() == 6) {
cosImageupload.delCOS(key.getId(), image);
} else if (key.getStorageType() == 7) {
ftpService.delFTP(key.getId(), image);
} else if (key.getStorageType() == 8) {
s3Imageupload.deleS3(key.getId(), image);
} else {
System.err.println("未获取到对象存储参数,删除失败。");
}
try {
imgAndAlbumService.deleteImgAndAlbum(image.getImgurl());
imgTempService.delImgAndExp(image.getImguid());
imgService.deleimg(image.getId());
ids.add(image.getId());
} catch (Exception e) {
e.printStackTrace();
System.err.println(image.getImgname() + ":图片数据库记录时发生错误");
}
} catch (Exception e) {
System.err.println("删除的时候发生了一些异常");
// ids.add(Long.valueOf(imgIds[i]));
e.printStackTrace();
}
}
msg.setData(ids);
return msg;
}
}
@@ -0,0 +1,98 @@
package cn.hellohao.utils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
/**
* base64转为multipartFile工具类
* base64Convert
*/
public class Base64ToMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
public Base64ToMultipartFile (byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imgContent);
// 关闭流,不然文件会一直占用资源,无法对其操作
byteArrayInputStream.close();
return byteArrayInputStream;
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
FileOutputStream fileOutputStream = new FileOutputStream(dest);
fileOutputStream.write(imgContent);
// 关闭流,不然文件会一直占用资源,无法对其操作
fileOutputStream.close();
}
/**
* base64转multipartFile
*
* @param base64
* @return
*/
public static MultipartFile base64Convert(String base64) {
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]);
}
}
@@ -1,59 +0,0 @@
package cn.hellohao.utils;
import java.io.*;
public class DeleImg {
public static void charu(String imgUrlText) {
String filePath =File.separator + "HellohaoData" ;
File file = new File(filePath);
File file1 = new File(filePath+File.separator+"img.ini");
if(!file.exists()){
file.mkdirs();
}
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw = null;
try {
//如果文件存在,则追加内容;如果文件不存在,则创建文件
fw = new FileWriter(file1, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(imgUrlText);
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取文件内容
public static String readFile(String path) {//路径
File file = new File(path);
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));//构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
result.append(System.lineSeparator() + s);
Print.Normal( s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
}
@@ -1,324 +0,0 @@
package cn.hellohao.utils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* <p>Title: </p>
* <p>Description: </p>
*
* @author Hellohao
* @date 2019年11月10日
*/
public class FTPUtils {
private final Logger LOGGER = LogManager.getLogger(getClass());
private FTPClient ftpClient = null;
private String server;
private int port;
private String userName;
private String userPassword;
public FTPUtils(String server, int port, String userName, String userPassword) {
this.server = server;
this.port = port;
this.userName = userName;
this.userPassword = userPassword;
}
public boolean open() {
// 判断是否已连接
if (ftpClient != null && ftpClient.isConnected()) {
return true;
}
try {
ftpClient = new FTPClient();
// 连接FTP服务器
ftpClient.connect(this.server, this.port);
ftpClient.login(this.userName, this.userPassword);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
Print.warning("FTP服务器拒绝连接.");
this.close();
System.exit(1);
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
return true;
} catch (Exception e) {
this.close();
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 切换到父目录</p>
* <p>Description: </p>
*
* @author Hellohao
* @date 2018年10月11日
*
* @return 切换结果 true:成功, false:失败
*/
private boolean changeToParentDir() {
try {
return ftpClient.changeToParentDirectory();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param dir 目的目录
* @return 切换结果 true:成功,false:失败
*/
private boolean cd(String dir) {
try {
return ftpClient.changeWorkingDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param filePath 指定的目录
* @return 文件列表,或者null
*/
private FTPFile[] getFileList(String filePath) {
try {
return ftpClient.listFiles(filePath);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param ftpPath 目的目录
* @return 切换结果
*/
public boolean changeDir(String ftpPath) {
if (!ftpClient.isConnected()) {
return false;
}
try {
char[] chars = ftpPath.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpPath = sbStr.toString();
if (ftpPath.indexOf('/') == -1) {
// 只有一层目录
ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8"));
} else {
// 多层目录循环创建
String[] paths = ftpPath.split("/");
for (int i = 0; i < paths.length; i++) {
ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8"));
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* @param ftpPath 需要创建的目录
* @return
*/
public boolean mkDir(String ftpPath) {
if (!ftpClient.isConnected()) {
return false;
}
try {
// 将路径中的斜杠统一
char[] chars = ftpPath.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpPath = sbStr.toString();
if (ftpPath.indexOf('/') == -1) {
// 只有一层目录
ftpClient.makeDirectory(new String(ftpPath.getBytes(), "UTF-8"));
ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8"));
} else {
// 多层目录循环创建
String[] paths = ftpPath.split("/");
for (int i = 0; i < paths.length; i++) {
ftpClient.makeDirectory(new String(paths[i].getBytes(), "UTF-8"));
ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8"));
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param //localDirectoryAndFileName 本地文件目录和文件名
* @param ftpFileName 上传到服务器的文件名()
* @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录(目录可以省略)
* @return
*/
public boolean upload(File srcFile, String ftpFileName, String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
boolean flag = false;
if (ftpClient != null) {
FileInputStream fis = null;
try {
fis = new FileInputStream(srcFile);
// 创建目录
this.mkDir(ftpDirectory);
ftpClient.setBufferSize(100000);
ftpClient.setControlEncoding("UTF-8");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
if (ftpFileName == null || ftpFileName == "") {
ftpFileName = srcFile.getName();
}
// 上传
flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "UTF-8"), fis);
} catch (Exception e) {
this.close();
e.printStackTrace();
return false;
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* @param ftpDirectoryAndFileName ftp服务器文件路径,以/dir形式开始
* @param localDirectoryAndFileName 保存到本地的目录
* @return
*/
public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
ftpClient.enterLocalPassiveMode();
try {
// 将路径中的斜杠统一
char[] chars = ftpDirectoryAndFileName.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpDirectoryAndFileName = sbStr.toString();
String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));
String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
this.changeDir(filePath);
ftpClient.retrieveFile(new String(fileName.getBytes(), "UTF-8"), new FileOutputStream(localDirectoryAndFileName)); // download
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param pathName
* @return
*/
public String[] getFileNameList(String pathName) {
try {
return ftpClient.listNames(pathName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* <p>Title: 删除FTP上的文件</p>
* <p>Description: </p>
* @param ftpDirAndFileName 路径开头不能加/,比如应该是test/filename1
* @return
*/
public boolean deleteFile(String ftpDirAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.deleteFile(ftpDirAndFileName);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* @param ftpDirectory
* @return
*/
public boolean deleteDirectory(String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.removeDirectory(ftpDirectory);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 关闭链接</p>
* <p>Description: </p>
*/
public void close() {
try {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
+97 -32
View File
@@ -1,13 +1,16 @@
package cn.hellohao.utils; package cn.hellohao.utils;
import org.omg.CORBA.Environment; import cn.hellohao.config.GlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.sql.SQLException; import java.io.FileWriter;
import java.util.Properties;
import java.util.UUID; import java.util.UUID;
/** /**
@@ -17,7 +20,7 @@ import java.util.UUID;
*/ */
@Configuration @Configuration
public class FirstRun implements InitializingBean { public class FirstRun implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(FirstRun.class);
@Value("${spring.datasource.username}") @Value("${spring.datasource.username}")
private String jdbcusername; private String jdbcusername;
@@ -27,24 +30,37 @@ public class FirstRun implements InitializingBean {
@Value("${spring.datasource.url}") @Value("${spring.datasource.url}")
private String jdbcurl; private String jdbcurl;
@Value("${DockerWebHost}")
private String DockerWebHost;
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() {
if(!DockerWebHost.contains("null")){
contentToTxt("/hellohaotbed/webapps/hellohao/config.json", "{\"serverHost\": \""+DockerWebHost+"\"}");
}
isWindows();
RunSqlScript.USERNAME = jdbcusername; RunSqlScript.USERNAME = jdbcusername;
RunSqlScript.PASSWORD = jdbcpass; RunSqlScript.PASSWORD = jdbcpass;
RunSqlScript.DBURL = jdbcurl; RunSqlScript.DBURL = jdbcurl;
Print.Normal("正在校验数据库参数..."); logger.info("正在校验数据库参数...");
RunSqlScript.RunInsert(dynamic); RunSqlScript.RunInsert(dynamic);
RunSqlScript.RunInsert(compressed); RunSqlScript.RunInsert(compressed);
String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
RunSqlScript.RunInsert("update user set uid='"+uid+"' where id = 1"); RunSqlScript.RunInsert("update user set uid='"+uid+"' where id = 1");
Integer ret0 =
RunSqlScript.RunSelectCount(judgeTable + "'keys' and column_name = 'Region'");
if (ret0 == 0) {
RunSqlScript.RunInsert(sql0);
Print.Normal("Add keys.Region||RootPath");
}
Integer ret1 = RunSqlScript.RunSelectCount(sql1); Integer ret1 = RunSqlScript.RunSelectCount(sql1);
if(ret1==0){ if(ret1==0){
Print.Normal("In execution..."); Print.Normal("In execution...");
RunSqlScript.RunInsert(sql2); RunSqlScript.RunInsert(sql2);
;
}else{ }else{
if(ret1>0){ if(ret1>0){
Print.Normal("Stage 1"); Print.Normal("Stage 1");
@@ -77,32 +93,40 @@ public class FirstRun implements InitializingBean {
RunSqlScript.RunInsert(sql8); RunSqlScript.RunInsert(sql8);
Print.Normal("Stage 6"); Print.Normal("Stage 6");
} }
Integer ret5 = RunSqlScript.RunSelectCount(judgeTable+"'config' and column_name = 'theme'");
if(ret5==0){
RunSqlScript.RunInsert(sql9);
Print.Normal("Stage 7");
}
Integer ret6 = RunSqlScript.RunSelectCount(judgeTable+"'imgandalbum' and column_name = 'notes' and TABLE_SCHEMA='picturebed'"); Integer ret6 = RunSqlScript.RunSelectCount(judgeTable+" 'user' and column_name = 'token'");
if(ret6==0){ if(ret6==0){
RunSqlScript.RunInsert(sql11); RunSqlScript.RunInsert(sql12);
Print.Normal("Stage 8"); Print.Normal("Add user.token");
} }
Integer isappclient = RunSqlScript.RunSelectCount(isTableName+"'appclient'");
RunSqlScript.RunInsert(sql10); if(isappclient==0){
Integer integer = RunSqlScript.RunInsert(createAppclient);
//RunSqlScript.RunInsert("alter table imgdata drop index index_md5key_url"); RunSqlScript.RunInsert(instartAppclient);
RunSqlScript.RunInsert(inddx_md5key); Print.Normal("Add table.appclient");
RunSqlScript.RunInsert("UPDATE `keys` SET `Endpoint` = '0' WHERE `id` = 8"); }
Integer isconfdata = RunSqlScript.RunSelectCount(isTableName+"'confdata'");
if(isconfdata==0){
RunSqlScript.RunInsert(createConfdata);
RunSqlScript.RunInsert(instartConfdata);
Print.Normal("Add table.confdata");
}
// RunSqlScript.RunInsert(inddx_md5key);
RunSqlScript.RunInsert("ALTER TABLE tbed.`user` MODIFY id int auto_increment;");
Print.Normal("Stage success"); Print.Normal("Stage success");
clears();
} }
//检查表是否存在,后边加'imgdata' and column_name = 'explains' 检查字段是否存在 //检查表是否存在,后边加'imgdata' and column_name = 'explains' 检查字段是否存在
private String judgeTable = "select count(*) from information_schema.columns where table_name = "; 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 //创建blacklist 2019-11-29
private String sql0 =
"alter table `keys` add (Region varchar(255) DEFAULT null,RootPath varchar(255) DEFAULT '/');";
private String sql1 = "select count(*) from information_schema.columns where table_name = 'uploadconfig' and column_name = 'blacklist'"; private String sql1 = "select count(*) from information_schema.columns where table_name = 'uploadconfig' and column_name = 'blacklist'";
private String sql2 = "alter table uploadconfig add blacklist varchar(500);"; private String sql2 = "alter table uploadconfig add blacklist varchar(500);";
//创建imgandalbum和album 添加imgdata表字段explain 2019-12-20 //创建imgandalbum和album 添加imgdata表字段explain 2019-12-20
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 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 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)"; private String sql6 = "alter table imgdata add explains varchar(5000)";
@@ -110,12 +134,17 @@ public class FirstRun implements InitializingBean {
private String sql7 = "alter table album add userid int(10)"; private String sql7 = "alter table album add userid int(10)";
//添加imgdata表字段md5key //添加imgdata表字段md5key
private String sql8 = "alter table imgdata add md5key varchar(5000)"; private String sql8 = "alter table imgdata add md5key varchar(5000)";
private String sql9 = "ALTER TABLE config ADD theme int(4) DEFAULT '1' COMMENT '主题' "; // 图片标识名字段
//修改字段长度 private String sql11 = "alter table `imgdata` add idname varchar(255) DEFAULT '未命名' ;";
private String sql10 = "alter table config modify column `explain` varchar(1000),modify column links varchar(1000),modify column notice varchar(1000),modify column baidu varchar(1000)";
//添加imgandalbum字段notes(添加画廊图片说明) private String sql12 = "alter table tbed.user add `token` varchar(255)";
private String sql11 = "alter table imgandalbum add notes varchar(1000) DEFAULT ' '"; //创建客户端程序相关表
private String createAppclient = "CREATE TABLE `appclient` (`id` varchar(10) NOT NULL,`isuse` varchar(10) NOT NULL,`winpackurl` varchar(255) NULL DEFAULT NULL,`macpackurl` varchar(255) NULL DEFAULT NULL,`appname` varchar(20) NULL,`applogo` varchar(255) NULL,`appupdate` varchar(10) NOT NULL) ";
private String instartAppclient = "INSERT INTO `appclient` VALUES ('app', 'on', NULL, NULL, 'Hellohao图像托管', 'https://hellohao.nos-eastchina1.126.net/TbedClient/app.png', '1.0.1');";
//创建confdata表
private String createConfdata = "CREATE TABLE tbed.confdata ( `key` varchar(100) NULL, jsondata LONGTEXT NULL )";
private String instartConfdata =
"INSERT INTO `confdata` VALUES ('config', '{\\\"sourcekey\\\":7,\\\"emails\\\":1,\\\"webname\\\":\\\"Hellohao图床\\\",\\\"explain\\\":\\\"Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。\\\",\\\"links\\\":\\\"<p style=\\\\\\\"color:#7c7c88;\\\\\\\">© 2019 <a href=\\\\\\\"http://www.Hellohao.cn/\\\\\\\" target=\\\\\\\"_blank\\\\\\\" title=\\\\\\\"Hellohao\\\\\\\">Hellohao</a><span> - All Rights Reserved</span> </p>\\\",\\\"notice\\\":\\\"也许...|这将是最好用的图床|为了更好的用户体验,建议您注册本站继续免费使用Hellohao图床。本站不得上传任何形式的非法图片,一旦发现,永久删除并禁封账户。情节严重者将相关资料交于相关部门处理。\\\",\\\"domain\\\":\\\"http://127.0.0.1:10088\\\",\\\"background1\\\":\\\"\\\",\\\"sett\\\":\\\"1\\\",\\\"webms\\\":\\\"Hellohao图像托管,是一家免费开源的图像托管,即时分享你的美好瞬间。\\\",\\\"webkeywords\\\":\\\"hellohao图床,图床,图片上传,开源图床,hellohao,图像托管,图片分享\\\",\\\"theme\\\":2,\\\"websubtitle\\\":\\\"这将是你用过最优秀的图像托管程序\\\",\\\"logo\\\":null,\\\"aboutinfo\\\":\\\"<img width=\\\\\\\"300px\\\\\\\" src=\\\\\\\"http://img.wwery.com/hellohao/rPscRYwz.png\\\\\\\"> <br /> <br /> <p>也许,这将是你用到最优秀的图像托管程序</p> <p>本程序为Hellohao图象托管程序</p> <br/> <p style=\\\\\\\"color: #656565;\\\\\\\">作者:hellohao独立开发</p> <p style=\\\\\\\"color: #656565;\\\\\\\">www.hellohao.cn</p>\\\"}');";
private String inddx_md5key = "ALTER TABLE imgdata ADD INDEX index_md5key_url ( md5key,imgurl)"; private String inddx_md5key = "ALTER TABLE imgdata ADD INDEX index_md5key_url ( md5key,imgurl)";
// create index yarn_app_result_i4 on yarn_app_result (flow_exec_id(100), another_column(50)); // create index yarn_app_result_i4 on yarn_app_result (flow_exec_id(100), another_column(50));
@@ -124,11 +153,11 @@ public class FirstRun implements InitializingBean {
private String compressed = "alter table imgdata row_format=compressed"; private String compressed = "alter table imgdata row_format=compressed";
private void clears(){ private void clears(){
File file1 = new File(File.separator+"HellohaoData"+File.separator+"hellohaotempimg"); File file1 = new File(GlobalConstant.LOCPATH+File.separator+"hellohaotempimg");
File file2 = new File(File.separator+"HellohaoData"+File.separator+"hellohaotempwatermarimg"); File file2 = new File(GlobalConstant.LOCPATH+File.separator+"hellohaotempwatermarimg");
//判断目录有没有创建 //判断目录有没有创建
File file = new File(File.separator+"HellohaoData"); File file = new File(GlobalConstant.LOCPATH);
if(!file.exists()){ if(!file.exists()){
file.mkdirs(); file.mkdirs();
file1.mkdirs(); file1.mkdirs();
@@ -143,4 +172,40 @@ public class FirstRun implements InitializingBean {
} }
public boolean isWindows() {
System.out.println("当前系统类型:"+System.getProperties().getProperty("os.name").toUpperCase());
if(System.getProperties().getProperty("os.name").toUpperCase().contains("MAC")){
GlobalConstant.SYSTYPE = "MAC";
Properties props=System.getProperties();
GlobalConstant.LOCPATH = props.getProperty("user.home")+File.separator+".HellohaoData";
}
return System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
}
public static void contentToTxt(String filePath, String content) {
// String str = new String(); //原有txt内容
String s1 = new String();//内容更新
try {
File f = new File(filePath);
if (f.exists()) {
System.out.print("文件存在");
} else {
System.out.print("文件不存在");
f.createNewFile();// 不存在则创建
}
// BufferedReader input = new BufferedReader(new FileReader(f));
// while ((str = input.readLine()) != null) {
// s1 += str + "\n";
// }
// input.close();
s1 += content + "\n";
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} }
@@ -1,8 +1,6 @@
package cn.hellohao.utils; package cn.hellohao.utils;
import cn.hellohao.service.impl.ImgServiceImpl; import cn.hellohao.service.impl.ImgServiceImpl;
import cn.hellohao.service.impl.ImgreviewServiceImpl;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/** /**
@@ -27,9 +25,6 @@ public class GetIPS implements Runnable {
thread.start(); thread.start();
} }
/*** * 用于测试跨域 * @author huangweii * 2015年5月29日 */
public static String getIpAddr(HttpServletRequest request){ public static String getIpAddr(HttpServletRequest request){
String ip = request.getHeader("X-Forwarded-For"); String ip = request.getHeader("X-Forwarded-For");
if(org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){ if(org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
+22 -11
View File
@@ -3,7 +3,8 @@ package cn.hellohao.utils;
import cn.hellohao.exception.StorageSourceInitException; import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.service.impl.*; import cn.hellohao.service.impl.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.util.Map; import java.util.Map;
@@ -13,15 +14,25 @@ import java.util.Map;
* @version 1.0 * @version 1.0
* @date 2019/11/7 17:12 * @date 2019/11/7 17:12
*/ */
@Service
public class GetSource { public class GetSource {
public static ReturnImage storageSource(Integer type, Map<String, File> fileMap, String userpath,Integer keyID){
NOSImageupload nosImageupload = SpringContextHolder.getBean(NOSImageupload.class); @Autowired
OSSImageupload ossImageupload = SpringContextHolder.getBean(OSSImageupload.class); NOSImageupload nosImageupload;
USSImageupload ussImageupload = SpringContextHolder.getBean(USSImageupload.class); @Autowired
KODOImageupload kodoImageupload = SpringContextHolder.getBean(KODOImageupload.class); OSSImageupload ossImageupload;
COSImageupload cosImageupload = SpringContextHolder.getBean(COSImageupload.class); @Autowired
FTPImageupload ftpImageupload = SpringContextHolder.getBean(FTPImageupload.class); USSImageupload ussImageupload;
UFileImageupload uFileImageupload = SpringContextHolder.getBean(UFileImageupload.class); @Autowired
KODOImageupload kodoImageupload;
@Autowired
COSImageupload cosImageupload;
@Autowired
FtpServiceImpl ftpService;
@Autowired
S3Imageupload s3Imageupload;
public ReturnImage storageSource(Integer type, Map<Map<String, String>, File> fileMap, String userpath,Integer keyID){
ReturnImage returnImage = null; ReturnImage returnImage = null;
try { try {
if(type==1){ if(type==1){
@@ -37,9 +48,9 @@ public class GetSource {
}else if(type==6){ }else if(type==6){
returnImage = cosImageupload.ImageuploadCOS(fileMap, userpath,keyID);; returnImage = cosImageupload.ImageuploadCOS(fileMap, userpath,keyID);;
}else if(type==7){ }else if(type==7){
returnImage = ftpImageupload.ImageuploadFTP(fileMap, userpath,keyID); returnImage = ftpService.FtpUploadFile(fileMap, userpath,keyID);
}else if(type==8){ }else if(type==8){
returnImage = uFileImageupload.ImageuploadUFile(fileMap, userpath,keyID); returnImage = s3Imageupload.ImageuploadS3(fileMap, userpath,keyID);
} }
else{ else{
new StorageSourceInitException("GetSource类捕捉异常:未找到存储源"); new StorageSourceInitException("GetSource类捕捉异常:未找到存储源");
@@ -90,12 +90,11 @@ public class ImgUrlUtil {
* @param savePath * @param savePath
* @throws IOException * @throws IOException
*/ */
public static Map<String ,Object> downLoadFromUrl(String urlStr, String fileName, String savePath){ public static Map<String ,Object> downLoadFromUrl(String urlStr,String fileName,String savePath){
Map<String ,Object> resmap = new HashMap<>(); Map<String ,Object> resmap = new HashMap<>();
Map<String ,String> map = checkURLStatusCode(urlStr); Map<String ,String> map = checkURLStatusCode(urlStr);
if(map.get("Check").equals("false")){ if(map.size()==0 || map.get("Check").equals("false")){
// StatusCode
resmap.put("res",false); resmap.put("res",false);
resmap.put("StatusCode",map.get("StatusCode")); resmap.put("StatusCode",map.get("StatusCode"));
return resmap; return resmap;
@@ -128,13 +127,14 @@ public class ImgUrlUtil {
//下载并且保存成功后 判断格式 如果不是图像格式 就删除 //下载并且保存成功后 判断格式 如果不是图像格式 就删除
// //
if(new File(saveDir+File.separator+fileName).exists()){ if(new File(saveDir+File.separator+fileName).exists()){
Msg msg = TypeDict.FileMiME(file,null); Msg msg = TypeDict.FileMiME(file);
if(msg.getCode().equals("200")){ if(msg.getCode().equals("200")){
File f = new File(saveDir+File.separator+fileName); File f = new File(saveDir+File.separator+fileName);
String imgPath = saveDir+File.separator+fileName+"."+(msg.getData().toString().replace("image/","")); String imgPath = saveDir+File.separator+fileName+"."+(msg.getData().toString().replace("image/",""));
f.renameTo(new File(imgPath)); f.renameTo(new File(imgPath));
resmap.put("res",true); resmap.put("res",true);
resmap.put("imgPath",imgPath); resmap.put("imgPath",imgPath);
resmap.put("imgsize",new File(imgPath).length());
}else{ }else{
new File(saveDir+File.separator+fileName).delete(); new File(saveDir+File.separator+fileName).delete();
resmap.put("res",false); resmap.put("res",false);

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