From 1941a3a7aae1daafcd48810e13d6d08bcec57c20 Mon Sep 17 00:00:00 2001 From: tiansh Date: Fri, 22 Oct 2021 19:08:08 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E7=89=88=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + pom.xml | 344 ++++++++----- .../java/cn/hellohao/TbedApplication.java | 9 +- .../cn/hellohao/auth/filter/OriginFilter.java | 69 +++ .../hellohao/auth/filter/SubjectFilter.java | 128 +++++ .../filter/xss}/XssFilter.java | 7 +- .../xss}/XssHttpServletRequestWrapper.java | 5 +- .../cn/hellohao/auth/shiro/ShiroConfig.java | 91 ++++ .../shiro/StatelessDefaultSubjectFactory.java | 14 + .../cn/hellohao/auth/shiro/UserRealm.java | 68 +++ .../java/cn/hellohao/auth/token/JWTUtil.java | 80 +++ .../token/StatelessDefaultSubjectFactory.java | 18 + src/main/java/cn/hellohao/config/SysName.java | 20 + .../hellohao/controller/AdminController.java | 252 +++++++-- .../controller/AdminRootController.java | 33 +- .../hellohao/controller/AlbumController.java | 16 +- .../hellohao/controller/ClientController.java | 453 ----------------- .../hellohao/controller/ErrorController.java | 6 +- .../hellohao/controller/IndexController.java | 401 +++++++++++++++ .../controller/UpdateImgController.java | 478 ------------------ .../hellohao/controller/UserController.java | 411 +++++++++------ .../java/cn/hellohao/dao/AlbumMapper.java | 3 +- .../java/cn/hellohao/dao/GroupMapper.java | 2 + src/main/java/cn/hellohao/dao/ImgMapper.java | 13 +- .../java/cn/hellohao/dao/ImgTempMapper.java | 20 + .../java/cn/hellohao/dao/ImgreviewMapper.java | 5 +- src/main/java/cn/hellohao/dao/KeysMapper.java | 2 +- src/main/java/cn/hellohao/dao/UserMapper.java | 2 +- .../interceptor/InterceptorConfig.java | 61 --- .../interceptor/InterceptorConfigTwo.java | 59 --- .../interceptor/InterceptorConfigWeb.java | 72 --- .../cn/hellohao/interceptor/WebAppConfig.java | 46 -- src/main/java/cn/hellohao/pojo/Config.java | 35 +- src/main/java/cn/hellohao/pojo/Images.java | 167 +++++- src/main/java/cn/hellohao/pojo/ImgTemp.java | 66 +++ .../java/cn/hellohao/pojo/ReturnImage.java | 35 +- src/main/java/cn/hellohao/pojo/User.java | 4 - .../hellohao/quartz/QuartzConfigration.java | 4 +- .../cn/hellohao/service/AlbumService.java | 2 + .../cn/hellohao/service/GroupService.java | 2 + .../cn/hellohao/service/IRedisService.java | 17 + .../java/cn/hellohao/service/ImgService.java | 13 +- .../cn/hellohao/service/ImgTempService.java | 17 + .../cn/hellohao/service/ImgreviewService.java | 2 + .../java/cn/hellohao/service/KeysService.java | 2 +- .../java/cn/hellohao/service/UserService.java | 2 +- .../hellohao/service/impl/AlbumServiceI.java | 5 + .../hellohao/service/impl/COSImageupload.java | 150 ++---- .../hellohao/service/impl/FTPImageupload.java | 204 +++----- .../service/impl/GroupServiceImpl.java | 11 + .../hellohao/service/impl/ImgServiceImpl.java | 28 +- .../service/impl/ImgTempServiceImpl.java | 36 ++ .../service/impl/ImgreviewServiceImpl.java | 6 + .../service/impl/InitializationStorage.java | 15 +- .../service/impl/KODOImageupload.java | 182 +++---- .../service/impl/KeysServiceImpl.java | 4 +- .../hellohao/service/impl/NOSImageupload.java | 157 ++---- .../hellohao/service/impl/OSSImageupload.java | 178 ++----- .../service/impl/RedisServiceImpl.java | 53 ++ .../service/impl/UFileImageupload.java | 157 ++---- .../hellohao/service/impl/USSImageupload.java | 147 ++---- .../hellohao/service/impl/UploadServicel.java | 451 +++++++++++------ .../service/impl/UserServiceImpl.java | 4 +- .../cn/hellohao/utils/GetCurrentSource.java | 57 ++- .../java/cn/hellohao/utils/GetSource.java | 24 +- .../java/cn/hellohao/utils/ImgUrlUtil.java | 122 ++++- .../java/cn/hellohao/utils/LocUpdateImg.java | 160 ++---- .../java/cn/hellohao/utils/NewSendEmail.java | 171 +++++++ .../java/cn/hellohao/utils/SendEmail.java | 93 ---- src/main/java/cn/hellohao/utils/SetFiles.java | 20 +- src/main/java/cn/hellohao/utils/SetText.java | 47 ++ src/main/java/cn/hellohao/utils/TypeDict.java | 27 + .../utils/verifyCode/IVerifyCodeGen.java | 31 ++ .../utils/verifyCode/RandomUtils.java | 48 ++ .../SimpleCharVerifyCodeGenImpl.java | 116 +++++ .../hellohao/utils/verifyCode/VerifyCode.java | 29 ++ src/main/resources/application.properties | 8 +- .../emailTemplate/emailFindPass.html | 12 + .../emailTemplate/emailRegister.html | 13 + src/main/resources/mapper/AlbumMapper.xml | 14 +- src/main/resources/mapper/ConfigMapper.xml | 10 +- src/main/resources/mapper/GroupMapper.xml | 15 + src/main/resources/mapper/ImgMapper.xml | 55 +- src/main/resources/mapper/ImgTempMapper.xml | 54 ++ src/main/resources/mapper/ImgreviewMapper.xml | 9 + src/main/resources/mapper/KeysMapper.xml | 2 +- src/main/resources/mapper/UserMapper.xml | 37 +- 87 files changed, 3644 insertions(+), 2875 deletions(-) create mode 100644 src/main/java/cn/hellohao/auth/filter/OriginFilter.java create mode 100644 src/main/java/cn/hellohao/auth/filter/SubjectFilter.java rename src/main/java/cn/hellohao/{interceptor => auth/filter/xss}/XssFilter.java (88%) rename src/main/java/cn/hellohao/{interceptor => auth/filter/xss}/XssHttpServletRequestWrapper.java (98%) create mode 100644 src/main/java/cn/hellohao/auth/shiro/ShiroConfig.java create mode 100644 src/main/java/cn/hellohao/auth/shiro/StatelessDefaultSubjectFactory.java create mode 100644 src/main/java/cn/hellohao/auth/shiro/UserRealm.java create mode 100644 src/main/java/cn/hellohao/auth/token/JWTUtil.java create mode 100644 src/main/java/cn/hellohao/auth/token/StatelessDefaultSubjectFactory.java create mode 100644 src/main/java/cn/hellohao/config/SysName.java create mode 100644 src/main/java/cn/hellohao/controller/IndexController.java delete mode 100644 src/main/java/cn/hellohao/controller/UpdateImgController.java create mode 100644 src/main/java/cn/hellohao/dao/ImgTempMapper.java delete mode 100644 src/main/java/cn/hellohao/interceptor/InterceptorConfig.java delete mode 100644 src/main/java/cn/hellohao/interceptor/InterceptorConfigTwo.java delete mode 100644 src/main/java/cn/hellohao/interceptor/InterceptorConfigWeb.java delete mode 100644 src/main/java/cn/hellohao/interceptor/WebAppConfig.java create mode 100644 src/main/java/cn/hellohao/pojo/ImgTemp.java create mode 100644 src/main/java/cn/hellohao/service/IRedisService.java create mode 100644 src/main/java/cn/hellohao/service/ImgTempService.java create mode 100644 src/main/java/cn/hellohao/service/impl/ImgTempServiceImpl.java create mode 100644 src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java create mode 100644 src/main/java/cn/hellohao/utils/NewSendEmail.java delete mode 100644 src/main/java/cn/hellohao/utils/SendEmail.java create mode 100644 src/main/java/cn/hellohao/utils/verifyCode/IVerifyCodeGen.java create mode 100644 src/main/java/cn/hellohao/utils/verifyCode/RandomUtils.java create mode 100644 src/main/java/cn/hellohao/utils/verifyCode/SimpleCharVerifyCodeGenImpl.java create mode 100644 src/main/java/cn/hellohao/utils/verifyCode/VerifyCode.java create mode 100644 src/main/resources/emailTemplate/emailFindPass.html create mode 100644 src/main/resources/emailTemplate/emailRegister.html create mode 100644 src/main/resources/mapper/ImgTempMapper.xml diff --git a/README.md b/README.md index fe710c7..90eaac2 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Core版:`本地`,`阿里OSS`,`又拍USS`,`七牛KODO`,`腾讯COS`,`网易NOS`, > 开源版正在开发中 作者正在夜以继日的努力开发中,敬请期待! +源代码不可用请谅解,如需搭建请前往下载编译包直接部署。 主站地址(包含Core版购买地址): [http://tbed.hellohao.cn/](http://tbed.hellohao.cn/) diff --git a/pom.xml b/pom.xml index e54f705..8962f9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,155 +1,27 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.springframework.boot spring-boot-starter-parent - 2.1.1.RELEASE + 2.5.1 cn.hellohao Tbed - Pro + 2.0-Free Tbed - Hellohao Picture Bed for Spring Boot - + Hellohao project for Spring Boot 1.8 - 9.0.30 - springboot + org.springframework.boot spring-boot-starter-thymeleaf - - com.alibaba - fastjson - 1.2.54 - - - com.netease.cloud - nos-sdk-java-publiccloud - 1.3.1 - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - com.aliyun.oss - aliyun-sdk-oss - 2.8.3 - - - - - javax.mail - mail - 1.4.7 - - - - org.springframework.boot - spring-boot-starter-mail - - - - com.baidu.aip - java-sdk - 4.11.0 - - - - com.upyun - java-sdk - 4.1.2 - - - - org.apache.commons - commons-text - 1.8 - - - - com.qiniu - qiniu-java-sdk - 7.2.22 - - - - com.qcloud - cos_api - 5.5.7 - - - - - - - - - - commons-net - commons-net - 3.3 - - - - - cn.hutool - hutool-all - 4.5.16 - - - - - org.quartz-scheduler - quartz - 2.3.2 - - - - org.springframework - spring-context-support - - - - - org.springframework - spring-tx - 4.3.16.RELEASE - - - - - org.fusesource - sigar - 1.6.4 - - - - org.slf4j - slf4j-api - 1.7.21 - - - commons-logging - commons-logging - 1.2 - - - - nekohtml - nekohtml - 1.9.6.2 - - org.springframework.boot spring-boot-starter-web @@ -157,41 +29,220 @@ org.mybatis.spring.boot mybatis-spring-boot-starter - 1.3.2 + 2.2.0 + + org.springframework.boot + spring-boot-devtools + runtime + true + mysql mysql-connector-java runtime + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + org.springframework.boot spring-boot-starter-test test + + + + + org.springframework.boot + spring-boot-starter-data-redis + 2.5.4 + + + + org.apache.shiro + shiro-spring + 1.7.1 + + + com.auth0 + java-jwt + 3.16.0 + + + + + + + + + + + org.apache.tika + tika-core + 2.0.0 + + + + + + org.springframework + spring-tx + 5.2.6.RELEASE + + + org.springframework.boot + spring-boot-starter-validation + + + + commons-logging + commons-logging + 1.2 + com.github.pagehelper pagehelper-spring-boot-starter - 1.2.10 + 1.2.12 - org.apache.httpcomponents httpclient - 4.5 + 4.5.12 org.apache.httpcomponents httpmime - 4.5 + 4.5.12 + + com.alibaba + fastjson + 1.2.54 + + + com.alibaba + druid-spring-boot-starter + 1.2.6 + + + io.pebbletemplates + pebble + 3.1.5 + + + + org.springframework.boot + spring-boot-starter-mail + 2.5.1 + + + + com.baidu.aip + java-sdk + 4.11.0 + + + net.coobird + thumbnailator + 0.4.11 + + + cn.hutool + hutool-all + 5.3.5 + + + org.quartz-scheduler + quartz + 2.3.2 + + + io.github.biezhi + oh-my-email + 0.0.4 + + + + + io.minio + minio + 7.1.0 + + + com.netease.cloud + nos-sdk-java-publiccloud + 1.3.1 + + + com.aliyun.oss + aliyun-sdk-oss + 3.10.2 + + + javax.xml.bind + jaxb-api + 2.3.1 + + + javax.activation + activation + 1.1.1 + + + + org.glassfish.jaxb + jaxb-runtime + 2.3.3 + + + + com.upyun + java-sdk + 4.1.2 + + + org.apache.commons + commons-text + 1.8 + + + com.qiniu + qiniu-java-sdk + 7.2.22 + + + com.qcloud + cos_api + 5.5.7 + + + commons-net + commons-net + 3.3 + + org.springframework spring-test - 5.1.9.RELEASE + 5.2.6.RELEASE compile + + + + + + + @@ -201,8 +252,21 @@ org.springframework.boot spring-boot-maven-plugin + - true + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true diff --git a/src/main/java/cn/hellohao/TbedApplication.java b/src/main/java/cn/hellohao/TbedApplication.java index a953294..682315a 100644 --- a/src/main/java/cn/hellohao/TbedApplication.java +++ b/src/main/java/cn/hellohao/TbedApplication.java @@ -11,7 +11,9 @@ import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.util.unit.DataSize; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -20,6 +22,7 @@ import java.util.Scanner; @SpringBootApplication @Configuration +@EnableScheduling @ServletComponentScan @EnableTransactionManagement(proxyTargetClass = true) public class TbedApplication { @@ -29,18 +32,14 @@ public static void main(String[] args) { } /** * 文件上传配置 - * * @return */ @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); // 单个数据大小 - factory.setMaxFileSize("102400KB"); // KB,MB + factory.setMaxFileSize(DataSize.parse("102400KB")); // KB,MB /// 总上传数据大小 - factory.setMaxRequestSize("102400KB"); - //factory.setLocation("/tmp"); - return factory.createMultipartConfig(); } diff --git a/src/main/java/cn/hellohao/auth/filter/OriginFilter.java b/src/main/java/cn/hellohao/auth/filter/OriginFilter.java new file mode 100644 index 0000000..ed7a99e --- /dev/null +++ b/src/main/java/cn/hellohao/auth/filter/OriginFilter.java @@ -0,0 +1,69 @@ +package cn.hellohao.auth.filter; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +import java.util.Collections; + +/** + * 跨域请求过滤器 + * + * @author Hellohao + * @date 2021/6/10 + */ +@Configuration +public class OriginFilter { + + @Value("${CROS_ALLOWED_ORIGINS}") + private String allowedOrigins; + + @SuppressWarnings("unchecked") + @Bean + public FilterRegistrationBean corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.setAllowCredentials(true); +// corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(allowedOrigins.replace(" ", ""))); + corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL)); + corsConfiguration.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL)); + corsConfiguration.setAllowedMethods(Collections.singletonList(CorsConfiguration.ALL)); + corsConfiguration.addExposedHeader("Authorization"); + source.registerCorsConfiguration("/**", corsConfiguration); + FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); + bean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return bean; + } + +} + + + +//@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); +// } +// +//} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java b/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java new file mode 100644 index 0000000..48d1a1e --- /dev/null +++ b/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java @@ -0,0 +1,128 @@ +package cn.hellohao.auth.filter; + +import cn.hellohao.auth.token.JWTUtil; +import cn.hellohao.pojo.User; +import cn.hellohao.service.impl.UserServiceImpl; +import cn.hellohao.utils.SpringContextHolder; +import cn.hutool.crypto.SecureUtil; +import com.alibaba.fastjson.JSONObject; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Hellohao + * @version 1.0 + * @date 2021/6/16 17:43 + */ + +public class SubjectFilter extends BasicHttpAuthenticationFilter { + + public static String WEBHOST = null; + private String CODE ="000"; + + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { + UserServiceImpl userService = SpringContextHolder.getBean(UserServiceImpl.class); + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse =(HttpServletResponse) response; + String serviceName = httpServletRequest.getServletPath();//获取接口 + String Users_Origin = httpServletRequest.getHeader("usersOrigin"); + + //验证前端域名 + if(httpServletRequest.getMethod().equals("POST") && !serviceName.contains("/api") && !serviceName.contains("/verifyCode")){ + try{ + if(Users_Origin.compareTo(SecureUtil.md5(WEBHOST))!=0){ + System.out.println("前端域名校验未通过"); + System.out.println("request-MD5:"+Users_Origin); + System.out.println("配置文件-MD5:"+SecureUtil.md5(WEBHOST)); + System.out.println("配置Host:"+WEBHOST); + this.CODE = "406"; + return false; + } + }catch (Exception e){ + e.printStackTrace(); + this.CODE = "500"; + return false; + } + } + //验证Token + String token = httpServletRequest.getHeader("Authorization"); + JSONObject jsonObject = JWTUtil.checkToken(token); + if(!jsonObject.getBoolean("check")){ + if(!serviceName.contains("admin")){ + return true; + }else{ + this.CODE = "403"; + return false; + } + }else{ + Subject subject = SecurityUtils.getSubject(); + User user = (User) subject.getPrincipal(); + //判断shiro里是否存有用户信息,如果没有,就再存进去。 + if(user==null){ +// System.out.println("Token没过期,但是Shiro里的用户信息空了,重新执行登录"); + //封装用户的登录数据(shiro认证的时候使用) + UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(jsonObject.getString("email"),jsonObject.getString("password")); + //设置记住我 + tokenOBJ.setRememberMe(true); + try { + //执行登录方法,如果没有异常,说明登录成功 + subject.login(tokenOBJ); + SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时 + } catch (Exception e) { + System.err.println("拦截器,登录失败,false"); + //e.printStackTrace(); + this.CODE = "403"; + return false; + } + }else{ + if(null!=user){ + try{ + if(null != user.getId()){ + if(userService.getUsers(user).getIsok()<1){ + subject.logout(); + this.CODE = "403"; + return false; + } + } + }catch (Exception e){ + System.out.println("拦截器判断用户isOK的时候报错了"); + e.printStackTrace(); + } + } + } + } + return true; + } + + protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) { + String info = "未知错误"; + try { + if(this.CODE.equals("405")){ + info = "当前请求域名认证失败"; + }else if(this.CODE.equals("406")){ + info = "前端域名配置不正确"; + }else if(this.CODE.equals("403")){ + info = "当前用户无权访问该请求"; + }else if(this.CODE.equals("402")){ + info = "当前web请求不合规"; + } + System.err.println("拦截器False-"+info); + response.setContentType("application/json;charset=UTF-8"); + final JSONObject jsonObject = new JSONObject(); + jsonObject.put("code",this.CODE); + jsonObject.put("info",info); + response.getWriter().write(jsonObject.toJSONString()); + } catch (Exception e) { + System.out.println("返回token验证失败403请求,报异常了"); + } + + return false; + } + +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/interceptor/XssFilter.java b/src/main/java/cn/hellohao/auth/filter/xss/XssFilter.java similarity index 88% rename from src/main/java/cn/hellohao/interceptor/XssFilter.java rename to src/main/java/cn/hellohao/auth/filter/xss/XssFilter.java index ceb0090..8a06a40 100644 --- a/src/main/java/cn/hellohao/interceptor/XssFilter.java +++ b/src/main/java/cn/hellohao/auth/filter/xss/XssFilter.java @@ -1,9 +1,10 @@ -package cn.hellohao.interceptor; +package cn.hellohao.auth.filter.xss; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; + /** * XSS过滤器 * @author hellohao @@ -12,7 +13,7 @@ import java.io.IOException; public class XssFilter implements Filter { @Override - public void init(javax.servlet.FilterConfig filterConfig) throws ServletException { + public void init(FilterConfig filterConfig) throws ServletException { } @@ -23,7 +24,7 @@ public class XssFilter implements Filter { //由于我的@WebFilter注解配置的是urlPatterns="/*"(过滤所有请求),所以这里对不需要过滤的静态资源url,作忽略处理(大家可以依照具体需求配置) String[] exclusionsUrls = {".js",".gif",".jpg",".png",".bmp",".css",".ico"};//,"/","/index","/admin/root/" for (String str : exclusionsUrls) { - System.out.println(path.contains(str)); + //System.out.println(path.contains(str)); if (path.contains(str)) { filterChain.doFilter(servletRequest,servletResponse); return; diff --git a/src/main/java/cn/hellohao/interceptor/XssHttpServletRequestWrapper.java b/src/main/java/cn/hellohao/auth/filter/xss/XssHttpServletRequestWrapper.java similarity index 98% rename from src/main/java/cn/hellohao/interceptor/XssHttpServletRequestWrapper.java rename to src/main/java/cn/hellohao/auth/filter/xss/XssHttpServletRequestWrapper.java index 28583df..799f98d 100644 --- a/src/main/java/cn/hellohao/interceptor/XssHttpServletRequestWrapper.java +++ b/src/main/java/cn/hellohao/auth/filter/xss/XssHttpServletRequestWrapper.java @@ -1,7 +1,8 @@ -package cn.hellohao.interceptor; +package cn.hellohao.auth.filter.xss; import com.alibaba.fastjson.JSON; import org.apache.commons.text.StringEscapeUtils; + import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; @@ -10,6 +11,7 @@ import java.io.*; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; + /** * ServletRequest包装类,对request做XSS过滤处理 * @author Hellohao @@ -87,6 +89,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { String line = ""; StringBuilder body = new StringBuilder(); int counter = 0; + // 读取POST提交的数据内容 BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8"))); try { diff --git a/src/main/java/cn/hellohao/auth/shiro/ShiroConfig.java b/src/main/java/cn/hellohao/auth/shiro/ShiroConfig.java new file mode 100644 index 0000000..3631e21 --- /dev/null +++ b/src/main/java/cn/hellohao/auth/shiro/ShiroConfig.java @@ -0,0 +1,91 @@ +package cn.hellohao.auth.shiro; + +import cn.hellohao.auth.filter.SubjectFilter; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.servlet.Filter; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author Hellohao + * @version 1.0 + * @date 2021/6/3 10:37 + */ + +@Configuration +public class ShiroConfig { + + + //shiro过滤对象 + @Bean//(name = "shiroFilterFactoryBean") + public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){ + ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); + //设置安全管理器 + bean.setSecurityManager(defaultWebSecurityManager); + Map filters = bean.getFilters(); +// Map filter = new HashMap<>(); + filters.put("JWT",new SubjectFilter()); + bean.setFilters(filters); + + //添加shiro内置过滤器 +/* + * anon: 无需认证就可以访问 + * authc: 必须认证了才可以访问 + * user: 必须拥有 记住我 功能才能访问 + * perms: 拥有对某个资源的权限才能访问 + * roles: 拥有某个角色的权限才能访问 + * */ + + Map filterMap = new LinkedHashMap<>(); + + //放行页面 + filterMap.put("/verifyCode","anon"); + filterMap.put("/verifyCodeForRegister","anon"); + filterMap.put("/verifyCodeForRetrieve","anon"); + filterMap.put("/api/**","anon"); + filterMap.put("/user/**","anon"); + filterMap.put("/ota/**","anon"); + filterMap.put("/admin/root/**","roles[admin]"); + filterMap.put("/**","JWT"); + + //认证失败的返回页面 + bean.setLoginUrl("/jurisError"); + //未授权页面 + bean.setUnauthorizedUrl("/authError"); + bean.setFilterChainDefinitionMap(filterMap); + return bean; + + } + + + //安全对象 + @Bean + public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ + DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); + //关联UserRealm + defaultWebSecurityManager.setRealm(userRealm); + defaultWebSecurityManager.setRememberMeManager(null); + return defaultWebSecurityManager; + } + + //创建 realm 对象 + @Bean(name = "userRealm") + public UserRealm userRealm(){ + return new UserRealm(); + } + + + //配置禁用session +// @Bean +// public StatelessDefaultSubjectFactory statelessDefaultSubjectFactory(){ +// StatelessDefaultSubjectFactory statelessDefaultSubjectFactory = new StatelessDefaultSubjectFactory(); +// return statelessDefaultSubjectFactory; +// } + +} + diff --git a/src/main/java/cn/hellohao/auth/shiro/StatelessDefaultSubjectFactory.java b/src/main/java/cn/hellohao/auth/shiro/StatelessDefaultSubjectFactory.java new file mode 100644 index 0000000..9565c19 --- /dev/null +++ b/src/main/java/cn/hellohao/auth/shiro/StatelessDefaultSubjectFactory.java @@ -0,0 +1,14 @@ +package cn.hellohao.auth.shiro; + +/** + * @author Hellohao + * @version 1.0 + * @date 2021/6/15 17:30 + */ +//public class StatelessDefaultSubjectFactory extends DefaultWebSecurityManager { +// //不创建Session +// public Subject createSubject(SubjectContext context){ +// context.setSessionCreationEnabled(false); +// return super.createSubject(context); +// } +//} diff --git a/src/main/java/cn/hellohao/auth/shiro/UserRealm.java b/src/main/java/cn/hellohao/auth/shiro/UserRealm.java new file mode 100644 index 0000000..20a58d2 --- /dev/null +++ b/src/main/java/cn/hellohao/auth/shiro/UserRealm.java @@ -0,0 +1,68 @@ +package cn.hellohao.auth.shiro; + +import cn.hellohao.pojo.User; +import cn.hellohao.service.UserService; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.apache.shiro.subject.Subject; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; + +/* + * @author Hellohao + * @version 1.0 + * @date 2021/6/3 10:39 + * 自定义UserRealm + +*/ +public class UserRealm extends AuthorizingRealm { + + @Autowired + private UserService userService; + + //授权 + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { +// System.out.println("..///执行了授权方法"); + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); + //拿到当前登录的对象 + Subject subject = SecurityUtils.getSubject(); + User user = (User) subject.getPrincipal(); + ArrayList roleList = new ArrayList(); + if(user.getLevel()==2){ + //赋予管理员权限 +// info.addRole("admin"); + roleList.add("admin"); + roleList.add("user"); +// info.addStringPermission("user:one"); + }else{ +// info.addRole("user"); + roleList.add("user"); + } + info.addRoles(roleList); + return info; + } + + //认证(登录) + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken tokenOBJ) throws AuthenticationException { +// System.out.println("执行了认证方法"); + UsernamePasswordToken userToken = null; + userToken = (UsernamePasswordToken)tokenOBJ; + User user = new User(); + user.setEmail(userToken.getUsername()); + User u = userService.getUsers(user); + //用户名认证 + if(u==null){ + //返回null 就是异常:UnknownAccountException + return null; + } + //密码认证(防止泄露,不需要我们做) + return new SimpleAuthenticationInfo(u,u.getPassword(),""); + } +} diff --git a/src/main/java/cn/hellohao/auth/token/JWTUtil.java b/src/main/java/cn/hellohao/auth/token/JWTUtil.java new file mode 100644 index 0000000..e49dc07 --- /dev/null +++ b/src/main/java/cn/hellohao/auth/token/JWTUtil.java @@ -0,0 +1,80 @@ +package cn.hellohao.auth.token; + +import cn.hellohao.pojo.User; +import com.alibaba.fastjson.JSONObject; +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.TokenExpiredException; +import com.auth0.jwt.interfaces.DecodedJWT; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * @author Hellohao + * @version 1.0 + * @date 2021/6/11 18:50 + */ +public class JWTUtil { + + private static String EXPIRE_TIME = ""; + private static String SECRET = "www.hellohao.cn"; + + //生成Token + public static String createToken(User user){ +// Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.SECOND,604800 );//单位秒,604800 为7天 + Algorithm algorithm = Algorithm.HMAC256(SECRET); + String token = JWT.create() + .withClaim("email", user.getEmail()) + .withClaim("username", user.getUsername()) + .withClaim("uid", user.getUid()) + .withClaim("password", user.getPassword()) + //到期时间 + .withExpiresAt(calendar.getTime()) + //创建一个新的JWT,并使用给定的算法进行标记 + .sign(algorithm); + return token; + } + + //验证Token + public static JSONObject checkToken(String token){ + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();//验证对象 + JSONObject jsonObject = new JSONObject(); + if(null==token){ + jsonObject.put("check",false); + return jsonObject; + } + try { + DecodedJWT verify = jwtVerifier.verify(token); + Date expiresAt = verify.getExpiresAt(); + jsonObject.put("check",true); + jsonObject.put("email",verify.getClaim("email").asString()); + jsonObject.put("password",verify.getClaim("password").asString()); + jsonObject.put("uid",verify.getClaim("uid").asString()); + } catch (TokenExpiredException e) { + e.printStackTrace(); + System.out.println("token认证已过期,请重新登录获取"); + jsonObject.put("check",false); + }catch (Exception e){ + e.printStackTrace(); + System.out.println("token无效"); + jsonObject.put("check",false); + } + return jsonObject; + } + + + 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"); + } +} diff --git a/src/main/java/cn/hellohao/auth/token/StatelessDefaultSubjectFactory.java b/src/main/java/cn/hellohao/auth/token/StatelessDefaultSubjectFactory.java new file mode 100644 index 0000000..c6885c7 --- /dev/null +++ b/src/main/java/cn/hellohao/auth/token/StatelessDefaultSubjectFactory.java @@ -0,0 +1,18 @@ +package cn.hellohao.auth.token; + +import org.apache.shiro.subject.Subject; +import org.apache.shiro.subject.SubjectContext; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; + +/** + * @author Hellohao + * @version 1.0 + * @date 2021/6/15 17:30 + */ +public class StatelessDefaultSubjectFactory extends DefaultWebSecurityManager { + //不创建Session + public Subject createSubject(SubjectContext context){ + context.setSessionCreationEnabled(false); + return super.createSubject(context); + } +} diff --git a/src/main/java/cn/hellohao/config/SysName.java b/src/main/java/cn/hellohao/config/SysName.java new file mode 100644 index 0000000..4cb05f0 --- /dev/null +++ b/src/main/java/cn/hellohao/config/SysName.java @@ -0,0 +1,20 @@ +package cn.hellohao.config; + +/** + * @author Tiansh + * @version 1.0 + * @date 2020/5/15 9:20 + */ +public class SysName { + public static final String SYSNAME = "root,hellohaocheck,selectdomain,image,hellohaocheck,HellohaoData,TOIMG," + + "user,users,admin,retrievepass,deleteimg,hellohaotempimg,360,hellohaotempwatermarimg,components,log"; + + public static Boolean CheckSysName(String name){ + boolean b = true; + if(SYSNAME.contains(name)){ + b = false; + } + return b ; + } + +} diff --git a/src/main/java/cn/hellohao/controller/AdminController.java b/src/main/java/cn/hellohao/controller/AdminController.java index 4d558ae..ccb5bca 100644 --- a/src/main/java/cn/hellohao/controller/AdminController.java +++ b/src/main/java/cn/hellohao/controller/AdminController.java @@ -11,6 +11,8 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -53,50 +55,73 @@ public class AdminController { @Autowired AlbumServiceI albumServiceI; - @RequestMapping(value = "/goadmin") - public String goadmin1(HttpSession session, Model model, HttpServletRequest request) { - Config config = configService.getSourceype(); - User user = (User) session.getAttribute("user"); + @PostMapping(value = "/overviewData") //new + @ResponseBody + public Msg overviewData(@RequestParam(value = "data", defaultValue = "") String data) { + Msg msg = new Msg(); + Subject subject = SecurityUtils.getSubject(); + User user = (User) subject.getPrincipal(); + user = userService.getUsers(user); + JSONObject jsonObject = new JSONObject(); UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); - Integer usermemory = imgService.getusermemory(user.getId()); - if(usermemory==null){usermemory=0;} - User u = userService.getUsers(user.getEmail()); - if(user!=null){ - if (user.getLevel() == 1) { - model.addAttribute("level", "普通用户"); - } else if (user.getLevel() == 2) { - model.addAttribute("level", "管理员"); - } else { - model.addAttribute("level", "未 知"); - } - model.addAttribute("levels", user.getLevel()); - model.addAttribute("username", user.getUsername()); - model.addAttribute("api", uploadConfig.getApi()); - model.addAttribute("config", config); - model.addAttribute("memory",u.getMemory());//单位M - if(usermemory==null){ - model.addAttribute("usermemory", 0);//单位M - }else{ - float d = (float) (Math.round((usermemory/1024.0F) * 100.0) / 100.0); - model.addAttribute("usermemory", d);//单位M - } - return "admin/index"; + Imgreview imgreview = imgreviewService.selectByPrimaryKey(1);//查询非法个数 + Imgreview isImgreviewOK = imgreviewService.selectByusing(1);//查询有没有启动鉴别功能 + //普通用户 + String ok = "false"; + jsonObject.put("myToken","这个去掉"); + jsonObject.put("myImgTotal", imgService.countimg(user.getId())); //我的图片数 + jsonObject.put("myAlbumTitle", albumService.selectAlbumCount(user.getId()));//我的画廊数量 + jsonObject.put("myView360Title", "0");//我的全景视图 + //计算自己的百分比 已用量/分配量 + long memory = Long.valueOf(user.getMemory());//分配量 + Long usermemory = imgService.getusermemory(user.getId())==null?0L:imgService.getusermemory(user.getId()); + if(memory==0){ + jsonObject.put("myMemory","无容量"); }else{ - System.out.println("重定向到首页"); - return "redirect:/"; + Double aDouble = Double.valueOf(String.format("%.2f", (((double)usermemory/(double)memory)*100))); + if(aDouble>=999){ + jsonObject.put("myMemory",999); + }else{ + jsonObject.put("myMemory",aDouble); + } } - } - - @RequestMapping(value = "/admin") - public String goadmin(HttpSession session, Model model) { - Config config = configService.getSourceype(); - User u = (User) session.getAttribute("user"); - model.addAttribute("username", u.getUsername()); - model.addAttribute("level", u.getLevel()); - model.addAttribute("email", u.getEmail()); - model.addAttribute("loginid", 100); - - return "admin/table"; + jsonObject.put("myMemorySum",SetFiles.readableFileSize(memory)); + if(user.getLevel()>1){ + ok = "true"; + //管理员 + jsonObject.put("imgTotal", imgService.counts(null) ); //admin 站点图片数 + jsonObject.put("userTotal", userService.getUserTotal()); //admin 用户个数 + jsonObject.put("ViolationImgTotal", imgreview.getCount()); //admin 非法图片 + jsonObject.put("ViolationSwitch", isImgreviewOK==null?0:isImgreviewOK.getId()); //admin 非法图片开关 + jsonObject.put("VisitorUpload", uploadConfig.getIsupdate());//是否禁用了游客上传 + jsonObject.put("VisitorMemory", SetFiles.readableFileSize(Long.valueOf(uploadConfig.getVisitormemory())));//访客共大小 + if(uploadConfig.getIsupdate()!=1){ + jsonObject.put("VisitorUpload", 0);//是否禁用了游客上传 + jsonObject.put("VisitorProportion",100.00);//游客用量%占比 + jsonObject.put("VisitorMemory", "禁用");//访客共大小 + }else{ + Long temp = imgService.getusermemory(0)==null?0:imgService.getusermemory(0); + jsonObject.put("UsedMemory", (temp == null ? 0 : SetFiles.readableFileSize(temp)));//访客已用大小 + if(Integer.valueOf(uploadConfig.getVisitormemory())==0){ + jsonObject.put("VisitorProportion",100.00);//游客用量%占比 + }else if(Integer.valueOf(uploadConfig.getVisitormemory())==-1){ + jsonObject.put("VisitorProportion",0);//游客用量%占比 + jsonObject.put("VisitorMemory", "无限");//访客共大小 + }else{ + double sum = Double.valueOf(uploadConfig.getVisitormemory()); + Double aDouble = Double.valueOf(String.format("%.2f", ((double) temp / sum) * 100)); + if(aDouble>=999){ + jsonObject.put("VisitorProportion",999);//游客用量%占比 + }else{ + jsonObject.put("VisitorProportion",aDouble);//游客用量%占比 + } + } + } + } + jsonObject.put("ok", ok); + //Config config = configService.getSourceype(); + msg.setData(jsonObject); + return msg; } @RequestMapping(value = "/tosurvey") @@ -112,9 +137,9 @@ public class AdminController { model.addAttribute("jdk", jdk); //空间大小 UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); - Integer usermemory = imgService.getusermemory(u.getId()); - if(usermemory==null){usermemory=0;} - User user = userService.getUsers(u.getEmail()); + Long usermemory = imgService.getusermemory(u.getId()); + if(usermemory==null){usermemory=0L;} + User user = userService.getUsers(u); if(u!=null){ if (u.getLevel() == 1) { model.addAttribute("level", "普通用户"); @@ -153,7 +178,7 @@ public class AdminController { if(uploadConfig.getIsupdate()!=1){ jsonObject.put("VisitorUpload", 0);//是否禁用了游客上传 }else{ - Integer temp = imgService.getusermemory(0); + Long temp = imgService.getusermemory(0); jsonObject.put("VisitorUpload", uploadConfig.getIsupdate());//是否禁用了游客上传 jsonObject.put("UsedSize", (temp == null ? 0 : temp/1024));//访客已用大小 jsonObject.put("VisitorMemory", uploadConfig.getVisitormemory());//访客共大小 @@ -161,6 +186,91 @@ public class AdminController { return jsonObject.toString(); } + @PostMapping("/getRecently")//new 获取榜单和最近上传 + @ResponseBody + public Msg getRecently(@RequestParam(value = "data", defaultValue = "") String data) { + Msg msg = new Msg(); + final JSONObject jsonObject = new JSONObject(); + try { + Subject subject = SecurityUtils.getSubject(); + User user = (User) subject.getPrincipal(); + user = userService.getUsers(user); + if(user.getLevel()>1){ + //管理员 可以看榜单数据 和最近上传 + jsonObject.put("RecentlyUser",imgService.RecentlyUser()); + jsonObject.put("RecentlyUploaded",imgService.RecentlyUploaded(user.getId())); + }else{ + //普通用户只能看最近上传 + jsonObject.put("RecentlyUploaded",imgService.RecentlyUploaded(user.getId())); + } + }catch (Exception e){ + e.printStackTrace(); + msg.setInfo("系统内部错误"); + msg.setCode("500"); + return msg; + } + msg.setData(jsonObject); + return msg; + } + + @PostMapping("/getYyyy")//new + @ResponseBody + public Msg getYyyy(@RequestParam(value = "data", defaultValue = "") String data){ + final Msg msg = new Msg(); + Subject subject = SecurityUtils.getSubject(); + User u = (User) subject.getPrincipal(); + final JSONObject jsonObject = new JSONObject(); + jsonObject.put("allYyyy",imgService.getyyyy(null)); + jsonObject.put("userYyyy",imgService.getyyyy(u.getId())); + msg.setData(jsonObject); + return msg; + } + + @PostMapping("/getChart")//new + @ResponseBody + public Msg getChart(@RequestParam(value = "data", defaultValue = "") String data){ + Msg msg = new Msg(); + JSONObject jsonObject = JSONObject.parseObject(data); + String yyyy = jsonObject.getString("yyyy"); + Integer type = jsonObject.getInteger("type"); + + Subject subject = SecurityUtils.getSubject(); + User u = (User) subject.getPrincipal(); + List list =null; + if(u.getLevel()>1){ + if(type==2){ + Images images = new Images(); + images.setYyyy(yyyy); + list = imgService.countByM(images); + }else{ + Images images = new Images(); + images.setYyyy(yyyy); + images.setUserid(u.getId()); + list = imgService.countByM(images); + } + }else{ + Images images = new Images(); + images.setYyyy(yyyy); + images.setUserid(u.getId()); + 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 jsonArray = new JSONArray(); + for (int j = 0; j < list.size(); j++) { + for (int i = 0; i < json.size(); i++) { + JSONObject jobj = json.getJSONObject(i); + if(jobj.getInteger("id")==list.get(j).getMonthNum()){ + jobj.put("monthNum",getChinaes(list.get(j).getMonthNum())); + jobj.put("countNum",list.get(j).getCountNum()); + } + } + } + msg.setData(json); + return msg; + } + + + @RequestMapping(value = "/selecttable") @ResponseBody @@ -230,7 +340,6 @@ public class AdminController { User u = (User) session.getAttribute("user"); Images images = imgService.selectByPrimaryKey(id); Keys key = keysService.selectKeys(sourcekey); - Integer Sourcekey = GetCurrentSource.GetSource(u.getId()); ImgServiceImpl de = new ImgServiceImpl(); if (key.getStorageType() == 1) { de.delect(key, images.getImgname()); @@ -274,7 +383,6 @@ public class AdminController { Integer v = 0; ImgServiceImpl de = new ImgServiceImpl(); User u = (User) session.getAttribute("user"); - Integer Sourcekey = GetCurrentSource.GetSource(u.getId()); for (int i = 0; i < ids.length; i++) { Keys key = keysService.selectKeys(sources[i]); if (key.getStorageType() == 1) { @@ -359,7 +467,7 @@ public class AdminController { public String kuorong(HttpSession session, String codestring) { User u = (User) session.getAttribute("user"); JSONObject jsonObject = new JSONObject(); - User u1 = userService.getUsers(u.getEmail()); + User u1 = userService.getUsers(u); Integer ret =0; Integer sizes = 0; if(u!=null){ @@ -448,4 +556,52 @@ public class AdminController { } + //工具函数 + 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; + + } + } diff --git a/src/main/java/cn/hellohao/controller/AdminRootController.java b/src/main/java/cn/hellohao/controller/AdminRootController.java index 263c5e8..3e774df 100644 --- a/src/main/java/cn/hellohao/controller/AdminRootController.java +++ b/src/main/java/cn/hellohao/controller/AdminRootController.java @@ -55,18 +55,18 @@ public class AdminRootController { @RequestMapping(value = "tostorage") public String tostorage(HttpSession session, Model model, HttpServletRequest request) { User u = (User) session.getAttribute("user"); - Integer Sourcekey = GetCurrentSource.GetSource(u.getId()); - Keys key= keysService.selectKeys(Sourcekey); + Group group = GetCurrentSource.GetSource(u.getId()); + Keys key= keysService.selectKeys(group.getKeyid()); //Boolean b = StringUtils.doNull(Sourcekey,key); Integer StorageType = 0; - if(Sourcekey!=5){ + if(key.getStorageType()!=5){ model.addAttribute("AccessKey", key.getAccessKey()); model.addAttribute("AccessSecret", key.getAccessSecret()); model.addAttribute("Endpoint", key.getEndpoint()); model.addAttribute("Bucketname", key.getBucketname()); model.addAttribute("RequestAddress", key.getRequestAddress()); - model.addAttribute("StorageType", Sourcekey); - if(Sourcekey==4){ + model.addAttribute("StorageType", key.getStorageType()); + if(key.getStorageType()==4){ model.addAttribute("Endpoint2", key.getEndpoint()); }else{ model.addAttribute("Endpoint2", 0); @@ -91,11 +91,11 @@ public class AdminRootController { @ResponseBody public Integer getkeyourceype(HttpSession session) { User u = (User) session.getAttribute("user"); - Integer Sourcekey = GetCurrentSource.GetSource(u.getId()); + Group group = GetCurrentSource.GetSource(u.getId()); + Keys key = keysService.selectKeys(group.getKeyid()); Integer ret = 0; - if(Sourcekey!=null){ - ret = Sourcekey; - } + + return ret; } @@ -170,19 +170,8 @@ public class AdminRootController { return ret; } - @RequestMapping(value = "/towebconfig") - public String towebconfig(HttpSession session,Model model) { - Config config = configService.getSourceype(); - User u = (User) session.getAttribute("user"); - Integer Sourcekey = GetCurrentSource.GetSource(u.getId()); - UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); - SysConfig sysConfig = sysConfigService.getstate(); - model.addAttribute("config",config); - model.addAttribute("updateConfig",updateConfig); - model.addAttribute("sysconfig",sysConfig); - model.addAttribute("group",Sourcekey); - return "admin/webconfig"; - } + + @PostMapping("/updateconfig") @ResponseBody public Integer updateconfig(Config config ) { diff --git a/src/main/java/cn/hellohao/controller/AlbumController.java b/src/main/java/cn/hellohao/controller/AlbumController.java index 01514cb..8b6a30e 100644 --- a/src/main/java/cn/hellohao/controller/AlbumController.java +++ b/src/main/java/cn/hellohao/controller/AlbumController.java @@ -36,20 +36,8 @@ public class AlbumController { @Autowired private UploadConfigService uploadConfigService; - @RequestMapping("/addalbum") - public String addalbum(HttpSession session,Model model) { - UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); - User u = (User) session.getAttribute("user"); - Integer sourcekey = 0; - if (u == null) { - sourcekey = GetCurrentSource.GetSource(null); - } else { - sourcekey = GetCurrentSource.GetSource(u.getId()); - } - model.addAttribute("urltype",updateConfig.getUrltype()); - model.addAttribute("sourcekey",sourcekey); - return "album/addalbum"; - } + + @PostMapping("/SaveForAlbum") @ResponseBody diff --git a/src/main/java/cn/hellohao/controller/ClientController.java b/src/main/java/cn/hellohao/controller/ClientController.java index 370b908..08d39c0 100644 --- a/src/main/java/cn/hellohao/controller/ClientController.java +++ b/src/main/java/cn/hellohao/controller/ClientController.java @@ -59,458 +59,5 @@ public class ClientController { @Value("${systemupdate}") private String systemupdate; - @PostMapping(value = "/clientupimg") - @ResponseBody - public ResultBean clientupimg(HttpServletRequest request,@RequestParam("file") List file, String email, String pass) throws Exception { - String userip = GetIPS.getIpAddr(request); - Print.Normal("上传者ip:"+userip); - ResultBean resultBean = null; - JSONArray jsonArray = new JSONArray(); - UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); - if (uploadConfig.getApi() == 1) { - if (email != null && pass != null) { - Integer ret = userService.login(email, Base64Encryption.encryptBASE64(pass.getBytes()),null); - if (ret > 0) { - User user = userService.getUsers(email); - if (user.getIsok() == 1) { - User u = userService.getUsers(email); - Config config = configService.getSourceype();//查询当前系统使用的存储源类型。 - Integer Sourcekey = GetCurrentSource.GetSource(u.getId()); - Keys key = keysService.selectKeys(Sourcekey); - if (key.getStorageType() != 0 && key.getStorageType() != null) { - if (key.getStorageType() == 1) { - nOSImageupload.Initialize(key);//实例化网易 - } else if (key.getStorageType() == 2) { - OSSImageupload.Initialize(key); - } else if (key.getStorageType() == 3) { - USSImageupload.Initialize(key); - } else if (key.getStorageType() == 4) { - KODOImageupload.Initialize(key); - } else if (key.getStorageType() == 6) { - COSImageupload.Initialize(key); - } else if (key.getStorageType() == 7) { - FTPImageupload.Initialize(key); - } else if(key.getStorageType()==8){ - UFileImageupload.Initialize(key); - }else { - System.err.println("客户端:未获取到对象存储参数,初始化失败。"); - } - } - Print.Normal("客户端:初始化上传。"); - long stime = System.currentTimeMillis(); - String userpath = "tourist"; - if (uploadConfig.getUrltype() == 2) { - java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); - userpath = dateFormat.format(new Date()); - } else { - if (u != null) { - userpath = u.getUsername(); - } - } - Map map = new HashMap<>(); - for (MultipartFile multipartFile : file) { - //获取文件名 - String fileName = multipartFile.getOriginalFilename(); - String lastname = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀 - if (!multipartFile.isEmpty()) { //判断文件是否为空 - map.put(lastname, multipartFile); - } - } - Map m = null; - Map m2 = null; - if (key.getStorageType() == 1) { - m = nOSImageupload.clientuploadNOS(map, userpath, uploadConfig); - } else if (key.getStorageType() == 2) { - m = ossImageupload.clientuploadOSS(map, userpath, uploadConfig); - } else if (key.getStorageType() == 3) { - m = ussImageupload.clientuploadUSS(map, userpath, uploadConfig); - } else if (key.getStorageType() == 4) { - m = kodoImageupload.clientuploadKODO(map, userpath, uploadConfig); - } else if (key.getStorageType() == 5) { - m2 = LocUpdateImg.clientLocUpdateImg(map, userpath, uploadConfig); - } else if (key.getStorageType() == 6) { - m = cosImageupload.clientuploadCOS(map, userpath, uploadConfig); - } else if (key.getStorageType() == 7) { - m = ftpImageupload.clientuploadFTP(map, userpath, uploadConfig); - } else if (key.getStorageType() == 8) { - m = uFileImageupload.clientuploadUSS(map, userpath, uploadConfig); - } else { - System.err.println("未获取到对象存储参数,上传失败。"); - } - Images img = new Images(); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); - String times = df.format(new Date()); - System.out.println("上传图片的时间是:" + times); - if (key.getStorageType() == 5) { - for (Map.Entry entry : m2.entrySet()) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Imgname", entry.getKey().getImgname()); - if (key.getStorageType() == 5) { - if (config.getDomain() != null) { - jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl()); - img.setImgurl(config.getDomain() + "/" + entry.getKey().getImgurl());//图片链接 - } else { - jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl()); - img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/" + entry.getKey().getImgurl());//图片链接 - } - } else { - jsonObject.put("Imgname", entry.getKey().getImgurl()); - img.setImgurl(entry.getKey().getImgurl());//图片链接 - } - img.setUpdatetime(times); - img.setSource(key.getStorageType()); - if (u == null) { - img.setUserid(0);//用户id - } else { - img.setUserid(u.getId());//用户id - } - img.setSizes((entry.getValue())); - img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); - img.setAbnormal(userip); - img.setImgtype(0); - //-1证明超出大小, - if (entry.getValue() != -1) { - userService.insertimg(img); - } - long etime = System.currentTimeMillis(); - System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms"); - jsonArray.add(jsonObject); - } - } else { - for (Map.Entry entry : m.entrySet()) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Imgname", entry.getKey().getImgname()); - if (key.getStorageType() == 5) { - if (config.getDomain() != null) { - jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl()); - img.setImgurl(config.getDomain() + "/" + entry.getKey().getImgurl());//图片链接 - } else { - jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl()); - img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/" + entry.getKey().getImgurl());//图片链接 - } - } else { - jsonObject.put("Imgurl", entry.getKey().getImgurl()); - img.setImgurl(entry.getKey().getImgurl());//图片链接 - } - img.setUpdatetime(times); - img.setSource(key.getStorageType()); - if (u == null) { - img.setUserid(0);//用户id - } else { - img.setUserid(u.getId());//用户id - } - img.setSizes((entry.getValue())/1024); - img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); - img.setAbnormal(userip); - img.setImgtype(0); - //-1证明超出大小, - if (entry.getValue() != -1) { - userService.insertimg(img); - } - long etime = System.currentTimeMillis(); - System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms"); - jsonArray.add(jsonObject); - } - } - resultBean = ResultBean.success(jsonArray); - } - } else {resultBean = ResultBean.error(-2, "此用户信息不正确。");} - } else {resultBean = ResultBean.error(-3, "邮箱密码为空");} - } - else{resultBean = ResultBean.error(-4, "管理员关闭了API接口");} - return resultBean; - } - - @PostMapping(value = "/clientupurlimg") - @ResponseBody - public ResultBean clientupurlimg( String imgurl, HttpServletRequest request, Integer setday, - String email,String pass) throws Exception { - String userip = GetIPS.getIpAddr(request); - Print.Normal("上传者ip:"+userip); - ResultBean resultBean = null; - UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); - if (uploadConfig.getApi() == 1) { - if (email != null && pass != null) { - Integer ret = userService.login(email, Base64Encryption.encryptBASE64(pass.getBytes()),null); - if (ret > 0) { - User u = userService.getUsers(email); - Config config = configService.getSourceype();//查询当前系统使用的存储源类型。 - Integer usermemory =0; - Integer memory =0; - Integer Sourcekey=0; - if(u==null){ - Sourcekey = GetCurrentSource.GetSource(null); - memory = uploadConfig.getVisitormemory(); - usermemory= imgService.getusermemory(0); - if(usermemory==null){usermemory = 0;} - }else{ - Sourcekey = GetCurrentSource.GetSource(u.getId()); - memory = userService.getUsers(u.getEmail()).getMemory(); - usermemory= imgService.getusermemory(u.getId()); - if(usermemory==null){usermemory = 0;} - } - String userpath = "tourist"; - if(uploadConfig.getUrltype()==2){ - java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd"); - userpath = dateFormat.format(new Date()); - }else{if (u != null) { userpath = u.getUsername();}} - JSONArray jsonArray = new JSONArray(); - - Keys key = keysService.selectKeys(Sourcekey); - long imgsize = ImgUrlUtil.getFileLength(imgurl); - Integer youke = uploadConfig.getFilesizetourists(); - Integer yonghu = uploadConfig.getFilesizeuser(); - String uuid= UUID.randomUUID().toString().replace("-", ""); -// //容量判断 - if(u==null){ - memory = uploadConfig.getVisitormemory(); - usermemory= imgService.getusermemory(0); - if(usermemory==null){usermemory = 0;} - }else{ - memory = userService.getUsers(u.getEmail()).getMemory(); - usermemory= imgService.getusermemory(u.getId()); - if(usermemory==null){usermemory = 0;} - } - Print.warning("上传地址是:"+request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"); - if(usermemory/10240 && imgsize<=(yonghu*1024*1024)){ - try{ - boolean bl =ImgUrlUtil.downLoadFromUrl(imgurl, - uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"); - if(bl==true){ - FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid); - byte[] b = new byte[3]; - is.read(b, 0, b.length); - String xxx = ImgUrlUtil.bytesToHexString(b); - xxx = xxx.toUpperCase(); - String ooo = TypeDict.checkType(xxx); - if(is!=null){ - is.close(); - } - if(!ooo.equals("0000")){ - Map map = new HashMap<>(); - map.put(ooo, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid); - Map m = null; - if(key.getStorageType()==1){ - m = nOSImageupload.Imageupload(null, userpath,map,setday); - }else if (key.getStorageType()==2){ - m = ossImageupload.ImageuploadOSS(null, userpath,map,setday); - }else if(key.getStorageType()==3 ){ - m = ussImageupload.ImageuploadUSS(null, userpath,map,setday); - }else if(key.getStorageType()==4){ - m = kodoImageupload.ImageuploadKODO(null, userpath,map,setday); - }else if(key.getStorageType()==5){ - m = LocUpdateImg.ImageuploadLOC(null,userpath,map,setday); - }else if(key.getStorageType()==6){ - m = cosImageupload.ImageuploadCOS(null,userpath,map,setday); - }else if(key.getStorageType()==7){ - m = ftpImageupload.ImageuploadFTP(null,userpath,map,setday); - }else if(key.getStorageType()==8){ - m = uFileImageupload.ImageuploadUSS(null, userpath,map,setday); - } - else{ - System.err.println("未获取到对象存储参数,上传失败。"); - } - Images img = new Images(); - SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); - String times = df.format(new Date()); - System.out.println("上传图片的时间是:"+times); - for (Map.Entry entry : m.entrySet()) { - if(key.getStorageType()==5){ - if(config.getDomain()!=null){ - jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl()); - img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接 - }else{ - jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl()); - img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接 - } - }else{ - jsonArray.add(entry.getKey().getImgurl()); - img.setImgurl(entry.getKey().getImgurl()); - } - img.setUpdatetime(times); - img.setSource(key.getStorageType()); - if (u == null) { - img.setUserid(0); - } else { - img.setUserid(u.getId()); - } - img.setSizes((entry.getValue())); - img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); - img.setAbnormal(userip); - img.setImgtype(0); - userService.insertimg(img); - long etime = System.currentTimeMillis(); - System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms"); - } - resultBean = ResultBean.success(jsonArray); - }else{ - resultBean = ResultBean.error(-3,"文件类型不符合要求"); - } - } - }catch (Exception e) { - // TODO: handle exception - Print.warning(e.toString()); - resultBean = ResultBean.error(-4,"该文件不支持上传"); - } - }else{ - resultBean = ResultBean.error(-2,"文件过大"); - } - }else{ - if(imgsize>0 && imgsize<=(youke*1024*1024)){ - try{ - boolean bl = ImgUrlUtil.downLoadFromUrl(imgurl, - uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"); - if(bl==true){ - FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid); - byte[] b = new byte[3]; - is.read(b, 0, b.length); - String xxx = ImgUrlUtil.bytesToHexString(b); - xxx = xxx.toUpperCase(); - String ooo = TypeDict.checkType(xxx); - if(is!=null){ - is.close(); - } - if(!xxx.equals("0000")){ - Map map = new HashMap<>(); - map.put(ooo, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid); - Map m = null; - if(key.getStorageType()==1){ - m = nOSImageupload.Imageupload(null, userpath,map,setday); - }else if (key.getStorageType()==2){ - m = ossImageupload.ImageuploadOSS(null, userpath,map,setday); - }else if(key.getStorageType()==3 ){ - m = ussImageupload.ImageuploadUSS(null, userpath,map,setday); - }else if(key.getStorageType()==4){ - m = kodoImageupload.ImageuploadKODO(null, userpath,map,setday); - }else if(key.getStorageType()==5){ - m =LocUpdateImg.ImageuploadLOC(null,userpath, map,setday); - }else if(key.getStorageType()==6){ - m =cosImageupload.ImageuploadCOS(null,userpath, map,setday); - }else if(key.getStorageType()==7){ - m = ftpImageupload.ImageuploadFTP(null,userpath,map,setday); - }else if(key.getStorageType()==8){ - m = uFileImageupload.ImageuploadUSS(null, userpath,map,setday); - } - else{ - System.err.println("未获取到对象存储参数,上传失败。"); - } - Images img = new Images(); - SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); - String times = df.format(new Date()); - System.out.println("上传图片的时间是:"+times); - for (Map.Entry entry : m.entrySet()) { - if(key.getStorageType()==5){ - if(config.getDomain()!=null){ - jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl()); - img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接 - }else{ - jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl()); - img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接 - } - }else{ - jsonArray.add(entry.getKey().getImgurl()); - img.setImgurl(entry.getKey().getImgurl());//图片链接 - } - img.setUpdatetime(times); - img.setSource(key.getStorageType()); - if (u == null) { - img.setUserid(0);//用户id - } else { - img.setUserid(u.getId());//用户id - } - img.setSizes((entry.getValue())); - img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); - img.setAbnormal(userip); - img.setImgtype(0); - userService.insertimg(img); - long etime = System.currentTimeMillis(); - System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms"); - } - resultBean = ResultBean.success(jsonArray); - }else{ - resultBean = ResultBean.error(-3,"文件类型不符合要求"); - } - } - }catch (Exception e) { - // TODO: handle exception - Print.warning(e.toString()); - resultBean = ResultBean.error(-4,"文件类型不符合要求"); - } - }else{ - resultBean = ResultBean.error(-2,"图片太大或不存在"); - } - } - }else{ - resultBean = ResultBean.error(-5,"可用空间不足"); - } - - }else {resultBean = ResultBean.error(-2, "此用户信息不正确。");} - }else {resultBean = ResultBean.error(-3, "邮箱或密码为空");} - }else{resultBean = ResultBean.error(-4, "管理员关闭了API接口");} -Print.Normal(resultBean.toString()); - return resultBean; - } - - @RequestMapping("/clientlogin") - @ResponseBody - public String login( HttpSession httpSession, String email, String password) { - JSONArray jsonArray = new JSONArray(); - String basepass = Base64Encryption.encryptBASE64(password.getBytes()); - Integer ret = userService.login(email, basepass,null); - if (ret > 0) { - User user = userService.getUsers(email); - if (user.getIsok() == 1) { - jsonArray.add(1); - } else if(ret==-1){ - jsonArray.add(-1); - }else { - jsonArray.add(-2); - } - } else { - jsonArray.add(0); - } - return jsonArray.toString(); - } - - @GetMapping (value = "/notices") - @ResponseBody - public String notices() throws Exception { - return "-1"; - } - - @GetMapping("/getNotice") - @ResponseBody - public Msg getNotice() { - Msg msg = new Msg(); - String url = "http://tc.hellohao.cn/getNoticeText"; - try { - URL u = new URL("http://tc.hellohao.cn/getNoticeText"); - HttpURLConnection uConnection = (HttpURLConnection) u.openConnection(); - uConnection.connect(); - System.out.println(uConnection.getResponseCode()); - if(uConnection.getResponseCode()==200){ - if(TestUrl.testUrlWithTimeOut(url,2000)){ - String urls =url; - msg.setData(HttpUtil.get(urls)); - }else{ - msg.setData("暂无公告"); - } - }else{ - msg.setData("暂无公告"); - } - uConnection.disconnect(); - } catch (Exception e) { - //e.printStackTrace(); - Print.warning("connect failed"); - msg.setData("暂无公告"); - } - return msg; - } - - - } diff --git a/src/main/java/cn/hellohao/controller/ErrorController.java b/src/main/java/cn/hellohao/controller/ErrorController.java index f2f4f5d..76ffd5b 100644 --- a/src/main/java/cn/hellohao/controller/ErrorController.java +++ b/src/main/java/cn/hellohao/controller/ErrorController.java @@ -28,8 +28,6 @@ class MainsiteErrorController implements ErrorController { } } - @Override - public String getErrorPath() { - return "error"; - } + + } \ No newline at end of file diff --git a/src/main/java/cn/hellohao/controller/IndexController.java b/src/main/java/cn/hellohao/controller/IndexController.java new file mode 100644 index 0000000..c36ff6c --- /dev/null +++ b/src/main/java/cn/hellohao/controller/IndexController.java @@ -0,0 +1,401 @@ +package cn.hellohao.controller; + +import cn.hellohao.auth.token.JWTUtil; +import cn.hellohao.pojo.*; +import cn.hellohao.service.*; +import cn.hellohao.service.impl.*; +import cn.hellohao.utils.*; +import cn.hellohao.utils.verifyCode.IVerifyCodeGen; +import cn.hellohao.utils.verifyCode.SimpleCharVerifyCodeGenImpl; +import cn.hellohao.utils.verifyCode.VerifyCode; +import cn.hutool.core.util.IdUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.imageio.ImageIO; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.awt.image.BufferedImage; +import java.io.*; +import java.text.SimpleDateFormat; +import java.util.*; + +@Controller +public class IndexController { + @Autowired + private SysConfigService sysConfigService; + @Autowired + IRedisService iRedisService; + @Autowired + private NOSImageupload nOSImageupload; + @Autowired + private UserService userService; + @Autowired + private KeysService keysService; + @Autowired + private ConfigService configService; + @Autowired + private UploadConfigService uploadConfigService; + @Autowired + private USSImageupload ussImageupload; + @Autowired + private KODOImageupload kodoImageupload; + @Autowired + private COSImageupload cosImageupload; + @Autowired + private FTPImageupload ftpImageupload; + @Autowired + private ImgService imgService; + @Autowired + private UploadServicel uploadServicel; + + private String[] iparr; + + public static String vu; + + + + @RequestMapping(value = "/webInfo")//upimg new + @ResponseBody + public Msg webInfo(HttpSession httpSession) { + final Msg msg = new Msg(); + Config config = configService.getSourceype(); + UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); + SysConfig sysConfig = sysConfigService.getstate(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("webname",config.getWebname()); + jsonObject.put("websubtitle",config.getWebsubtitle()); + jsonObject.put("keywords",config.getWebkeywords()); + jsonObject.put("description",config.getWebms()); + jsonObject.put("explain",config.getExplain()); + jsonObject.put("favicon",config.getWebfavicons()); + jsonObject.put("baidu",config.getBaidu()); + jsonObject.put("links",config.getLinks()); + jsonObject.put("aboutinfo",config.getAboutinfo()); + jsonObject.put("logo",config.getLogo()); + jsonObject.put("api",updateConfig.getApi()); +// jsonObject.put("watermark",updateConfig.getWatermark()); +// jsonObject.put("guidepage",sysConfig.getGuidepage()); + jsonObject.put("register",sysConfig.getRegister()); + msg.setData(jsonObject); + return msg; + } + + + @PostMapping(value = "/upload")//upimg new + @ResponseBody + public Msg upimg(HttpServletRequest request,HttpSession httpSession + , @RequestParam(value = "file", required = false) MultipartFile multipartFile,Integer day, + @RequestParam(value = "classifications", defaultValue = "" ) String classifications) { + final JSONArray jsonArray = new JSONArray(); + if(!classifications.equals("")){ + 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("/sentence") + @ResponseBody + public String sentence(HttpSession session, Integer id) { + JSONArray jsonArray = new JSONArray(); + String text = Sentence.getURLContent(); + jsonArray.add(text); + return jsonArray.toString(); + } + + + @RequestMapping(value = "/getUploadInfo")//new + @ResponseBody + public Msg getUploadInfo() { + Msg msg = new Msg(); + JSONObject jsonObject = new JSONObject(); + Subject subject = SecurityUtils.getSubject(); + User user = (User) subject.getPrincipal(); + try { + UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); + jsonObject.put("suffix",updateConfig.getSuffix().split(",")); + if(null==user){ + jsonObject.put("filesize",Integer.valueOf(updateConfig.getFilesizetourists())/1024); + jsonObject.put("imgcount",updateConfig.getImgcounttourists()); + jsonObject.put("uploadSwitch",updateConfig.getIsupdate()); + jsonObject.put("uploadInfo","您登陆后才能使用此功能哦"); + }else{ + jsonObject.put("filesize",Integer.valueOf(updateConfig.getFilesizeuser())/1024); + jsonObject.put("imgcount",updateConfig.getImgcountuser()); + } + }catch (Exception e){ + e.printStackTrace(); + } + msg.setData(jsonObject); + return msg; + } + + + @RequestMapping("/checkStatus") + @ResponseBody + public Msg checkStatus( HttpSession httpSession,HttpServletRequest request) { + Msg msg = new Msg(); + String token = request.getHeader("Authorization"); + if(token != null) { + JSONObject tokenJson = JWTUtil.checkToken(token); +// boolean check = (boolean) result.get("check"); +// String password = (String) result.get("password"); + if(tokenJson.getBoolean("check")){ + //获取当前用户 + Subject subject = SecurityUtils.getSubject(); + //封装用户的登录数据(shiro认证的时候使用) + UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(tokenJson.getString("email"),tokenJson.getString("password")); + //设置记住我 + tokenOBJ.setRememberMe(true); + try { + //执行登录方法,如果没有异常,说明登录成功 + subject.login(tokenOBJ); + SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时 + User u = (User) subject.getPrincipal(); + final JSONObject jsonObject = new JSONObject(); + jsonObject.put("RoleLevel",u.getLevel()==2?"admin":"user"); + msg.setCode("200"); + msg.setData(jsonObject); + } catch (Exception e) { + //此异常说明用户名不存在 + msg.setCode("40041"); + msg.setInfo("登录失效,请重新登录"); + System.err.println("登录失效,请重新登录"); + e.printStackTrace(); + } + }else{ + msg.setCode("40041"); + msg.setInfo("登录失效,请重新登录"); + } + }else{ + msg.setCode("40040"); + msg.setInfo("当前未登录,请先登录"); + } + return msg; + } + + + + @GetMapping("/verifyCode") + public void verifyCode(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) { + IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl(); + try { + //登录页面验证码 + VerifyCode verifyCode = iVerifyCodeGen.generate(80, 38); + String code = verifyCode.getCode(); + String userIP = GetIPS.getIpAddr(request); + iRedisService.setValue(userIP+"_hellohao_verifyCode",code); + response.setHeader("Pragma", "no-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setDateHeader("Expires", 0); + response.setContentType("image/jpeg"); + response.getOutputStream().write(verifyCode.getImgBytes()); + response.getOutputStream().flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @GetMapping("/verifyCodeForRegister") + public void verifyCodeForRegister(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) { + IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl(); + try { + VerifyCode verifyCode = iVerifyCodeGen.generate(80, 38); + String code = verifyCode.getCode(); + String userIP = GetIPS.getIpAddr(request); + iRedisService.setValue(userIP+"_hellohao_verifyCodeForRegister",code); + response.setHeader("Pragma", "no-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setDateHeader("Expires", 0); + response.setContentType("image/jpeg"); + response.getOutputStream().write(verifyCode.getImgBytes()); + response.getOutputStream().flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @GetMapping("/verifyCodeForRetrieve") + public void verifyCodeForRetrieve(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) { + IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl(); + try { + VerifyCode verifyCode = iVerifyCodeGen.generate(80, 38); + String code = verifyCode.getCode(); + System.out.println("verifyCodeForRetrieve-zhaoHui httpSession ID==="+httpSession.getId()); + String userIP = GetIPS.getIpAddr(request); + iRedisService.setValue(userIP+"_hellohao_verifyCodeForEmailRetrieve",code); + response.setHeader("Pragma", "no-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setDateHeader("Expires", 0); + response.setContentType("image/jpeg"); + response.getOutputStream().write(verifyCode.getImgBytes()); + response.getOutputStream().flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @GetMapping(value = "/images/{id}") + @ResponseBody + public Images selectByFy(@PathVariable("id") Integer id) { + return imgService.selectByPrimaryKey(id); + } + + + @RequestMapping("/{key1}/TOIMG{key2}N.{key3}") + public ResponseEntity selectByFyOne(final HttpServletRequest request, + HttpServletResponse response, + @PathVariable("key1") String key1, @PathVariable("key2") String key2, + @PathVariable("key3") String key3, Model model){ + MediaType mediaType =null; + File file = new File(File.separator+"HellohaoData"+File.separator+key1+"/TOIMG"+key2+"N."+key3); + if (!file.exists()) { + try { + response.sendRedirect("/404"); + } catch (IOException e) { + e.printStackTrace(); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("

404 FILE NOT FOUND

"); + } + } + if(key3.equals("png")){ + mediaType = MediaType.IMAGE_PNG; + }else if(key3.equals("gif")){ + mediaType = MediaType.IMAGE_GIF; + }else{ + mediaType = MediaType.IMAGE_JPEG; + } + HttpHeaders headers = new HttpHeaders(); + headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); + // headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName())); + headers.add("Pragma", "no-cache"); + headers.add("Expires", "0"); + headers.add("Last-Modified", new Date().toString()); + headers.add("ETag", String.valueOf(System.currentTimeMillis())); + return ResponseEntity + .ok() + .headers(headers) + .contentLength(file.length()) + .contentType(mediaType) + .body(new FileSystemResource(file)); + + //return "forward:/links/"+key1+"/TOIMG"+key2+"N."+key3; + } + + // @RequestMapping("/{key1:\\d+}/{key2}/{key3}/TOIMG{key4}N.{key5}") + public void selectByFy2(HttpServletRequest request, HttpServletResponse response, + @PathVariable("key1") String key1,@PathVariable("key2") String key2, + @PathVariable("key3") String key3,@PathVariable("key4") String key4, + @PathVariable("key5") String key5,Model model) { + String head = "jpg"; + if(key5.equals("jpg")||key5.equals("jpeg")){ + head = "jpeg"; + }else if(key5.equals("png")){ + head = "png"; + }else if(key5.equals("bmp")){ + head = "bmp"; + }else if(key5.equals("gif")){ + head = "gif"; + }else{ + head = key5; + } + response.setHeader("Pragma", "no-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setDateHeader("Expires", 0); + response.setContentType("image/"+head); + //InputStream is= null; + BufferedImage bi=null; + try { + //is = new FileInputStream(new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5)); + bi= ImageIO.read(new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5)); + //is.close(); + //将图片输出给浏览器 + BufferedImage image = (bi) ; + OutputStream os = response.getOutputStream(); + ImageIO.write(image, head, os); + } catch (Exception e) { + Print.warning("寻找本地文件出错:"+e.getMessage()); + e.printStackTrace(); + try { + response.sendRedirect("/404"); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + @GetMapping("/{key1:\\d+}/{key2}/{key3}/TOIMG{key4}N.{key5}") + @ResponseBody + public ResponseEntity selectByFyTow(final HttpServletRequest request, + HttpServletResponse response, + @PathVariable("key1") String key1, + @PathVariable("key2") String key2, + @PathVariable("key3") String key3, + @PathVariable("key4") String key4, + @PathVariable("key5") String key5) { + MediaType mediaType =null; + File file = new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5); + if (!file.exists()) { + try { + response.sendRedirect("/404"); + } catch (IOException e) { + e.printStackTrace(); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("

404 FILE NOT FOUND

"); + } + } + if(key5.equals("png")){ + mediaType = MediaType.IMAGE_PNG; + }else if(key5.equals("gif")){ + mediaType = MediaType.IMAGE_GIF; + }else{ + mediaType = MediaType.IMAGE_JPEG; + } + HttpHeaders headers = new HttpHeaders(); + headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); + // headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName())); + headers.add("Pragma", "no-cache"); + headers.add("Expires", "0"); + headers.add("Last-Modified", new Date().toString()); + headers.add("ETag", String.valueOf(System.currentTimeMillis())); + return ResponseEntity + .ok() + .headers(headers) + .contentLength(file.length()) + .contentType(mediaType) + .body(new FileSystemResource(file)); + } + + private Integer yzupdate(){ + Calendar cal = Calendar.getInstance(); + int y=cal.get(Calendar.YEAR); + int m=cal.get(Calendar.MONTH); + int d=cal.get(Calendar.DATE); + //int h=cal.get(Calendar.HOUR_OF_DAY); + //int mm=cal.get(Calendar.MINUTE); + return y+m+d+999; + } + + @RequestMapping("/err") + public String err() { + return "err"; + } + + +} diff --git a/src/main/java/cn/hellohao/controller/UpdateImgController.java b/src/main/java/cn/hellohao/controller/UpdateImgController.java deleted file mode 100644 index bce650c..0000000 --- a/src/main/java/cn/hellohao/controller/UpdateImgController.java +++ /dev/null @@ -1,478 +0,0 @@ -package cn.hellohao.controller; - -import cn.hellohao.pojo.*; -import cn.hellohao.service.*; -import cn.hellohao.service.impl.*; -import cn.hellohao.utils.*; -import cn.hutool.core.util.IdUtil; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import org.apache.commons.text.StringEscapeUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.FileSystemResource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import javax.imageio.ImageIO; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.awt.image.BufferedImage; -import java.io.*; -import java.text.SimpleDateFormat; -import java.util.*; - -@Controller -public class UpdateImgController { - @Autowired - private NOSImageupload nOSImageupload; - @Autowired - private UserService userService; - @Autowired - private KeysService keysService; - @Autowired - private ConfigService configService; - @Autowired - private UploadConfigService uploadConfigService; - @Autowired - private USSImageupload ussImageupload; - @Autowired - private KODOImageupload kodoImageupload; - @Autowired - private COSImageupload cosImageupload; - @Autowired - private FTPImageupload ftpImageupload; - @Autowired - private ImgService imgService; - @Autowired - private UploadServicel uploadServicel; - - private String[] iparr; - - public static String vu; - - @RequestMapping({"/", "/index"}) - public String indexImg(Model model, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) { - Print.Normal("当前项目路径:"+System.getProperty("user.dir")); - Config config = configService.getSourceype(); - UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); - User u = (User) httpSession.getAttribute("user"); - String email = (String) httpSession.getAttribute("email"); - Integer filesizetourists = 0; - Integer filesizeuser = 0; - Integer imgcounttourists = 0; - Integer imgcountuser = 0; - if(uploadConfig.getFilesizetourists()!=null){filesizetourists = uploadConfig.getFilesizetourists();} - if(uploadConfig.getFilesizeuser()!=null){filesizeuser = uploadConfig.getFilesizeuser();} - if(uploadConfig.getImgcounttourists()!=null){imgcounttourists = uploadConfig.getImgcounttourists();} - if(uploadConfig.getImgcountuser()!=null){imgcountuser = uploadConfig.getImgcountuser();} - if (email != null) { - Integer ret = userService.login(u.getEmail(), u.getPassword(),null); - if (ret > 0) { - User user = userService.getUsers(u.getEmail()); - model.addAttribute("username", user.getUsername()); - model.addAttribute("level", user.getLevel()); - model.addAttribute("loginid", 100); - model.addAttribute("imgcount", imgcountuser); - model.addAttribute("filesize", filesizeuser*1024*1024); - } else { - model.addAttribute("loginid", -1); - model.addAttribute("imgcount", imgcounttourists); - } - } else { - model.addAttribute("loginid", -2); - model.addAttribute("imgcount", imgcounttourists); - model.addAttribute("filesize", filesizetourists*1024*1024); - } - model.addAttribute("suffix", uploadConfig.getSuffix()); - model.addAttribute("config", config); - model.addAttribute("uploadConfig", uploadConfig); - Integer isupdate = 1; - if(uploadConfig.getIsupdate()!=1){ - isupdate = (u == null) ? 0: 1; - } - model.addAttribute("VisitorUpload", isupdate); - vu = IdUtil.simpleUUID(); - model.addAttribute("vu",vu); - if(config.getTheme()==1){ - return "index"; - }else{ - return "index-Minimalism"; - } - } - - @RequestMapping(value = "/upimg") - @ResponseBody - public Msg upimg( HttpSession session,HttpServletRequest request - , @RequestParam(value = "file", required = false) MultipartFile multipartFile,Integer setday,String upurlk) throws Exception { - Msg msg = new Msg(); - msg = uploadServicel.uploadForLoc(session,request,multipartFile,setday,upurlk,iparr); - return msg; - } - - //根据网络图片url上传 - @PostMapping(value = "/upurlimg") - @ResponseBody - public String upurlimg(HttpSession session, String imgurl, HttpServletRequest request,Integer setday,String upurlk) throws Exception { - JSONArray jsonArray = new JSONArray(); - Config config = configService.getSourceype(); - UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); - User u = (User) session.getAttribute("user"); - Integer usermemory =0; - Integer memory =0; - Integer Sourcekey=0; - String userpath = "tourist"; - String userip = GetIPS.getIpAddr(request); - Print.Normal("上传者ip:"+userip); - iparr = uploadConfig.getBlacklist().split(";"); - for (String s : iparr) { - if(s.equals(userip)){ - jsonArray.add(911); - return jsonArray.toString(); - } - } - if(u==null){ - Sourcekey = GetCurrentSource.GetSource(null); - memory = uploadConfig.getVisitormemory(); - usermemory= imgService.getusermemory(0); - if(usermemory==null){usermemory = 0;} - }else{ - userpath = u.getUsername(); - Sourcekey = GetCurrentSource.GetSource(u.getId()); - memory = userService.getUsers(u.getEmail()).getMemory(); - usermemory= imgService.getusermemory(u.getId()); - if(usermemory==null){usermemory = 0;} - } - if(uploadConfig.getUrltype()==2){ - java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd"); - userpath = dateFormat.format(new Date()); - } - //if(Integer.parseInt(Base64Encryption.decryptBASE64(upurlk))!=yzupdate()){ - if (!upurlk.equals(UpdateImgController.vu)) { - jsonArray.add(-403); - return jsonArray.toString(); - } - Keys key = keysService.selectKeys(Sourcekey); - long imgsize = ImgUrlUtil.getFileLength(imgurl); - Integer youke = uploadConfig.getFilesizetourists(); - Integer yonghu = uploadConfig.getFilesizeuser(); - String uuid= UUID.randomUUID().toString().replace("-", ""); - //Boolean bo =false; - //bo = Sourcekey==5?true:StringUtils.doNull(Sourcekey,key); -// if(!bo){ -// jsonArray.add(-1); -// return jsonArray.toString(); -// } - Print.warning("上传地址是:"+request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"); - - if(usermemory/1024>=memory) { - jsonArray.add(-5); - return jsonArray.toString(); - } - long stime = System.currentTimeMillis(); - if(u!=null){ - if(imgsize>0 && imgsize>=(yonghu*1024*1024)) { - jsonArray.add(-2); - return jsonArray.toString(); - } - try{ - boolean bl =ImgUrlUtil.downLoadFromUrl(imgurl, - uuid, request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator); - if(bl==true){ - FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator+uuid); - byte[] b = new byte[3]; - is.read(b, 0, b.length); - String xxx = ImgUrlUtil.bytesToHexString(b); - xxx = xxx.toUpperCase(); - if(is!=null){is.close();} - if(TypeDict.checkType(xxx).equals("0000")) { - jsonArray.add(-3);//不是图片格式 - return jsonArray.toString(); - } - Map map = new HashMap<>(); - map.put(TypeDict.checkType(xxx), request.getSession().getServletContext().getRealPath("/")+"hellohaotmp"+ File.separator+uuid); - Map m = null; - m = GetSource.storageSource(key.getStorageType(), null, userpath,map,setday); - Images img = new Images(); - SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); - String times = df.format(new Date()); - System.out.println("上传图片的时间是:"+times); - for (Map.Entry entry : m.entrySet()) { - if(key.getStorageType()==5){ - if(config.getDomain()!=null){ - jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl()); - img.setImgurl(config.getDomain()+"/"+entry.getKey().getImgurl());//图片链接 - }else{ - jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl()); - img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/"+entry.getKey().getImgurl());//图片链接 - } - }else{ - jsonArray.add(entry.getKey().getImgurl()); - img.setImgurl(entry.getKey().getImgurl()); - } - img.setUpdatetime(times); - img.setSource(key.getStorageType()); - img.setUserid(u == null?0:u.getId()); - img.setSizes((entry.getValue())); - //img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); - img.setImgname(entry.getKey().getImgurl()); - img.setAbnormal(userip); - if(setday>0){img.setImgtype(1);} - else{img.setImgtype(0);} - userService.insertimg(img); - long etime = System.currentTimeMillis(); - System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms"); - } - } - }catch (Exception e) { - Print.warning(e.toString()); - jsonArray.add(-4); - } - }else{ - if(imgsize>0 && imgsize>=(youke*1024*1024)){ - //文件过大 - jsonArray.add(-2); - return jsonArray.toString(); - } - try{ - boolean bl = ImgUrlUtil.downLoadFromUrl(imgurl, - uuid, request.getSession().getServletContext().getRealPath("/")+"hellohaotmp"+File.separator); - if(bl==true){ - FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"hellohaotmp"+File.separator+uuid); - byte[] b = new byte[3]; - is.read(b, 0, b.length); - String xxx = ImgUrlUtil.bytesToHexString(b); - xxx = xxx.toUpperCase(); - if(is!=null){is.close(); } - if(xxx.equals("0000")) { - jsonArray.add(-3); - return jsonArray.toString(); - } - Map map = new HashMap<>(); - map.put(TypeDict.checkType(xxx), request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator+uuid); - Map m = null; - m = GetSource.storageSource(key.getStorageType(), null, userpath,map,setday); - Images img = new Images(); - SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); - String times = df.format(new Date()); - System.out.println("上传图片的时间是:"+times); - for (Map.Entry entry : m.entrySet()) { - if(key.getStorageType()==5){ - if(config.getDomain()!=null){ - jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl()); - img.setImgurl(config.getDomain()+"/"+entry.getKey().getImgurl()); - }else{ - jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl()); - img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/"+entry.getKey().getImgurl());//图片链接 - } - }else{ - jsonArray.add(entry.getKey().getImgurl()); - img.setImgurl(entry.getKey().getImgurl()); - } - img.setUpdatetime(times); - img.setSource(key.getStorageType()); - img.setUserid(u == null?0:u.getId()); - img.setSizes((entry.getValue())); - img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); - img.setImgtype(setday>0?1:0); - img.setAbnormal(userip); - userService.insertimg(img); - long etime = System.currentTimeMillis(); - System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms"); - } - } - }catch (Exception e) { - Print.warning(e.toString()); - jsonArray.add(-4); - } - } - return jsonArray.toString(); -/** - * 错误返回值含义: - * -1 存储源key未配置 - * -2 目标图片太大或者不存在 - * -3 文件类型不符合要求 - * */ - } - - @RequestMapping("/sentence") - @ResponseBody - public String sentence(HttpSession session, Integer id) { - JSONArray jsonArray = new JSONArray(); - String text = Sentence.getURLContent(); - jsonArray.add(text); - return jsonArray.toString(); - } - - //ajax查询用户是否已经登录 - @RequestMapping(value = "/islogin") - @ResponseBody - public String islogin(HttpSession session) { - JSONObject jsonObject = new JSONObject(); - User user = (User) session.getAttribute("user"); - if(user!=null){ - if (user.getEmail() != null && user.getPassword() != null) { - jsonObject.put("username",user.getUsername()); - jsonObject.put("level",user.getLevel()); - jsonObject.put("lgoinret",1); - }else{ - jsonObject.put("lgoinret",0); - } - } - return jsonObject.toString(); - } - - @GetMapping(value = "/images/{id}") - @ResponseBody - public Images selectByFy(@PathVariable("id") Integer id) { - return imgService.selectByPrimaryKey(id); - } - - - @RequestMapping("/{key1}/TOIMG{key2}N.{key3}") - public ResponseEntity selectByFyOne(final HttpServletRequest request, - HttpServletResponse response, - @PathVariable("key1") String key1, @PathVariable("key2") String key2, - @PathVariable("key3") String key3, Model model){ - MediaType mediaType =null; - File file = new File(File.separator+"HellohaoData"+File.separator+key1+"/TOIMG"+key2+"N."+key3); - if (!file.exists()) { - try { - response.sendRedirect("/404"); - } catch (IOException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("

404 FILE NOT FOUND

"); - } - } - if(key3.equals("png")){ - mediaType = MediaType.IMAGE_PNG; - }else if(key3.equals("gif")){ - mediaType = MediaType.IMAGE_GIF; - }else{ - mediaType = MediaType.IMAGE_JPEG; - } - HttpHeaders headers = new HttpHeaders(); - headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); - // headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName())); - headers.add("Pragma", "no-cache"); - headers.add("Expires", "0"); - headers.add("Last-Modified", new Date().toString()); - headers.add("ETag", String.valueOf(System.currentTimeMillis())); - return ResponseEntity - .ok() - .headers(headers) - .contentLength(file.length()) - .contentType(mediaType) - .body(new FileSystemResource(file)); - - //return "forward:/links/"+key1+"/TOIMG"+key2+"N."+key3; - } - - // @RequestMapping("/{key1:\\d+}/{key2}/{key3}/TOIMG{key4}N.{key5}") - public void selectByFy2(HttpServletRequest request, HttpServletResponse response, - @PathVariable("key1") String key1,@PathVariable("key2") String key2, - @PathVariable("key3") String key3,@PathVariable("key4") String key4, - @PathVariable("key5") String key5,Model model) { - String head = "jpg"; - if(key5.equals("jpg")||key5.equals("jpeg")){ - head = "jpeg"; - }else if(key5.equals("png")){ - head = "png"; - }else if(key5.equals("bmp")){ - head = "bmp"; - }else if(key5.equals("gif")){ - head = "gif"; - }else{ - head = key5; - } - response.setHeader("Pragma", "no-cache"); - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expires", 0); - response.setContentType("image/"+head); - //InputStream is= null; - BufferedImage bi=null; - try { - //is = new FileInputStream(new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5)); - bi= ImageIO.read(new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5)); - //is.close(); - //将图片输出给浏览器 - BufferedImage image = (bi) ; - OutputStream os = response.getOutputStream(); - ImageIO.write(image, head, os); - } catch (Exception e) { - Print.warning("寻找本地文件出错:"+e.getMessage()); - e.printStackTrace(); - try { - response.sendRedirect("/404"); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } - - @GetMapping("/{key1:\\d+}/{key2}/{key3}/TOIMG{key4}N.{key5}") - @ResponseBody - public ResponseEntity selectByFyTow(final HttpServletRequest request, - HttpServletResponse response, - @PathVariable("key1") String key1, - @PathVariable("key2") String key2, - @PathVariable("key3") String key3, - @PathVariable("key4") String key4, - @PathVariable("key5") String key5) { - MediaType mediaType =null; - File file = new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5); - if (!file.exists()) { - try { - response.sendRedirect("/404"); - } catch (IOException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("

404 FILE NOT FOUND

"); - } - } - if(key5.equals("png")){ - mediaType = MediaType.IMAGE_PNG; - }else if(key5.equals("gif")){ - mediaType = MediaType.IMAGE_GIF; - }else{ - mediaType = MediaType.IMAGE_JPEG; - } - HttpHeaders headers = new HttpHeaders(); - headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); - // headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName())); - headers.add("Pragma", "no-cache"); - headers.add("Expires", "0"); - headers.add("Last-Modified", new Date().toString()); - headers.add("ETag", String.valueOf(System.currentTimeMillis())); - return ResponseEntity - .ok() - .headers(headers) - .contentLength(file.length()) - .contentType(mediaType) - .body(new FileSystemResource(file)); - } - - private Integer yzupdate(){ - Calendar cal = Calendar.getInstance(); - int y=cal.get(Calendar.YEAR); - int m=cal.get(Calendar.MONTH); - int d=cal.get(Calendar.DATE); - //int h=cal.get(Calendar.HOUR_OF_DAY); - //int mm=cal.get(Calendar.MINUTE); - return y+m+d+999; - } - - @RequestMapping("/err") - public String err() { - return "err"; - } - - -} diff --git a/src/main/java/cn/hellohao/controller/UserController.java b/src/main/java/cn/hellohao/controller/UserController.java index fa6809c..663ed48 100644 --- a/src/main/java/cn/hellohao/controller/UserController.java +++ b/src/main/java/cn/hellohao/controller/UserController.java @@ -1,36 +1,29 @@ package cn.hellohao.controller; -import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.List; import java.util.Random; import java.util.UUID; - -import javax.mail.internet.MimeMessage; -import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import javax.validation.Valid; - +import cn.hellohao.auth.filter.SubjectFilter; +import cn.hellohao.auth.token.JWTUtil; +import cn.hellohao.config.SysName; import cn.hellohao.pojo.*; import cn.hellohao.service.*; -import cn.hellohao.utils.Base64Encryption; -import cn.hellohao.utils.Print; -import cn.hellohao.utils.SendEmail; +import cn.hellohao.utils.*; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.IncorrectCredentialsException; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.alibaba.fastjson.JSONArray; +import org.springframework.web.bind.annotation.*; import com.alibaba.fastjson.JSONObject; -import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user") @@ -47,170 +40,276 @@ public class UserController { private SysConfigService sysConfigService; @Autowired private UserGroupService userGroupService; + @Autowired + IRedisService iRedisService; - @RequestMapping("/register") + @PostMapping("/register") @ResponseBody - public String Register(@Valid User u,Integer zctmp) { - JSONObject jsonObject = new JSONObject(); - if((zctmp-number2)==(istmp2-number2)){ + public Msg Register(HttpServletRequest request,@RequestParam(value = "data", defaultValue = "") String data) {//Validated + Msg msg = new Msg(); + JSONObject jsonObj = JSONObject.parseObject(data); + String username = jsonObj.getString("username"); + String email = jsonObj.getString("email"); + String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes()); + String userIP = GetIPS.getIpAddr(request); + String verifyCodeForRegister = jsonObj.getString("verifyCode"); + Object redis_verifyCodeForRegister = iRedisService.getValue(userIP+"_hellohao_verifyCodeForRegister"); + + if(!SetText.checkEmail(email)){ + //邮箱格式不正确 + msg.setCode("110403"); + msg.setInfo("邮箱格式不正确"); + return msg; + } + String regex = "^\\w+$"; + if(username.length()>20 || !username.matches (regex)){ + //用户名格式不正确 + msg.setCode("110403"); + msg.setInfo("用户名不得超过20位字符"); + return msg; + } + if(null==redis_verifyCodeForRegister){ + msg.setCode("4035"); + msg.setInfo("验证码已失效,请重新弄获取。"); + return msg; + }else if(null==verifyCodeForRegister){ + msg.setCode("4036"); + msg.setInfo("验证码不能为空。"); + return msg; + } + if((redis_verifyCodeForRegister.toString().toLowerCase()).compareTo((verifyCodeForRegister.toLowerCase()))==0){ User user = new User(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); EmailConfig emailConfig = emailConfigService.getemail(); - Integer countusername = userService.countusername(u.getUsername()); - Integer countmail = userService.countmail(u.getEmail()); + Integer countusername = userService.countusername(username); + Integer countmail = userService.countmail(email); SysConfig sysConfig = sysConfigService.getstate(); - if(sysConfig.getRegister()==1){ - if (countusername == 0 && countmail == 0) { - String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式 - String birthder = df.format(new Date());// new Date()为获取当前系统时间 - user.setLevel(1); - user.setUid(uid); - user.setBirthder(birthder); - user.setMemory(updateConfig.getUsermemory()); - user.setGroupid(1); - user.setEmail(u.getEmail()); - user.setUsername(u.getUsername()); - user.setPassword(Base64Encryption.encryptBASE64(u.getPassword().getBytes())); - Config config = configService.getSourceype(); - System.err.println("是否启用了邮箱激活:"+emailConfig.getUsing()); - Integer type = 0; - if(emailConfig.getUsing()==1){ - user.setIsok(0); - MimeMessage message = SendEmail.Emails(emailConfig); - //注册完发激活链接 - Thread thread = new Thread() { - public void run() { - Integer a = SendEmail.sendEmail(message, user.getUsername(), uid, user.getEmail(),emailConfig,config); - } - }; - thread.start(); - type = 1; - }else{ - //直接注册 - user.setIsok(1); - type = 2; + if(sysConfig.getRegister()!=1){ + msg.setCode("110403"); + msg.setInfo("本站已暂时关闭用户注册功能"); + return msg; + } + if(countusername == 1 || !SysName.CheckSysName(username)){ + msg.setCode("110406"); + msg.setInfo("此用户名已存在"); + return msg; + } + if(countmail == 1){ + msg.setCode("110407"); + msg.setInfo("此邮箱已被注册"); + return msg; + } + String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 + String birthder = df.format(new Date());// new Date()为获取当前系统时间 + user.setLevel(1); + user.setUid(uid); + user.setBirthder(birthder); + user.setMemory(updateConfig.getUsermemory()); + user.setGroupid(1); + user.setEmail(email); + user.setUsername(username); + user.setPassword(password); + Config config = configService.getSourceype(); + Integer type = 0; + if(emailConfig.getUsing()==1){ + user.setIsok(0); + //注册完发激活链接 + Thread thread = new Thread() { + public void run() { + Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), uid, user.getEmail(),config); } - Integer ret = userService.register(user); - if(ret>0){ - } - jsonObject.put("ret",ret); - jsonObject.put("zctype",type); - } else { - jsonObject.put("ret",-2); - } + }; + thread.start(); + msg.setInfo("注册成功,请注意查收邮箱尽快激活账户"); }else{ - jsonObject.put("ret",-3); //管理员关闭的注册 + //直接注册 + user.setIsok(1); + msg.setInfo("注册成功,快去登陆吧"); + } + userService.register(user); + }else{ + msg.setCode("110408"); + msg.setInfo("验证码不正确");//失效也要处理。 + } + return msg; + } + + //shiro登录认证 + @PostMapping("/login")//new + @ResponseBody + public Msg login(HttpServletRequest request,@RequestParam(value = "data", defaultValue = "") String data) { + Msg msg = new Msg(); + JSONObject jsonObj = JSONObject.parseObject(data); + String email = jsonObj.getString("email"); + String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes()); + String verifyCode = jsonObj.getString("verifyCode"); + String userIP = GetIPS.getIpAddr(request); + Object redis_VerifyCode = iRedisService.getValue(userIP+"_hellohao_verifyCode"); + if(null==redis_VerifyCode){ + msg.setCode("4035"); + msg.setInfo("验证码已失效,请重新弄获取。"); + return msg; + }else if(null==verifyCode){ + msg.setCode("4036"); + msg.setInfo("验证码不能为空。"); + return msg; + } + if((redis_VerifyCode.toString().toLowerCase()).compareTo((verifyCode.toLowerCase()))==0){ +// if(true){ + //获取当前用户 + Subject subject = SecurityUtils.getSubject(); + //封装用户的登录数据(shiro认证的时候使用) + UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(email,password); + //设置记住我 + tokenOBJ.setRememberMe(true); + try { + //执行登录方法,如果没有异常,说明登录成功 + subject.login(tokenOBJ); + SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时 + JSONObject jsonObject = new JSONObject(); + User user = (User) SecurityUtils.getSubject().getPrincipal(); + if(user.getIsok()==0){ + msg.setInfo("你的账号暂未激活"); + msg.setCode("110403"); + return msg; + } + if(user.getIsok()<0){ + msg.setInfo("你的账户已被冻结"); + msg.setCode("110403"); + return msg; + } +// String token = TokenUtil.sign(user); + String token = JWTUtil.createToken(user); + Subject su = SecurityUtils.getSubject(); + System.out.println("当前用户角色:admin:"+su.hasRole("admin")); + msg.setInfo("登录成功"); + jsonObject.put("token",token); + jsonObject.put("RoleLevel",user.getLevel()==2?"admin":"user"); + msg.setData(jsonObject); + return msg; + } catch (UnknownAccountException e) { + //此异常说明用户名不存在 + msg.setCode("4000"); + msg.setInfo("登录邮箱不存在"); + System.err.println("邮箱不存在"); + e.printStackTrace(); + return msg; + }catch (IncorrectCredentialsException e) { + msg.setCode("4000"); + msg.setInfo("登录密码错误"); + System.err.println("密码不存在"); + e.printStackTrace(); + return msg; + }catch (Exception e) { + msg.setCode("5000"); + msg.setInfo("登录失败"); + System.err.println("登录失败"); + e.printStackTrace(); + return msg; } }else{ - jsonObject.put("ret",-4);//非法注册 + msg.setCode("40034"); + msg.setInfo("验证码不正确");//失效也要处理。 } - return jsonObject.toString(); - } - - - @RequestMapping("/login") - @ResponseBody - public String login( HttpServletResponse response,HttpSession httpSession, String email, String password,Integer logotmp) { - JSONArray jsonArray = new JSONArray(); - if((logotmp-number1)==(istmp1-number1)){ - String basepass = Base64Encryption.encryptBASE64(password.getBytes()); - Integer ret = userService.login(email, basepass,null); - if (ret > 0) { - User user = userService.getUsers(email); - if (user.getIsok() == 1) { - httpSession.setAttribute("user", user); - httpSession.setAttribute("email", user.getEmail()); - Cookie cookie = new Cookie("Hellohao_UniqueUserKey", userService.getUsers(user.getEmail()).getUid()); - cookie.setMaxAge(60*60*24*90); - cookie.setPath("/"); - response.addCookie(cookie); - jsonArray.add(1); - } else if(ret==-1){ - jsonArray.add(-1); - }else { - jsonArray.add(-2); - } - } else { - jsonArray.add(0); - } - }else{jsonArray.add(-3);//非法登录 - } - - return jsonArray.toString(); - } - - - @RequestMapping("/login_c") - @ResponseBody - public String login( HttpSession httpSession, String Hellohao_UniqueUserKey) { - JSONArray jsonArray = new JSONArray(); - Integer ret = userService.login(null, null,Hellohao_UniqueUserKey); - if (ret > 0) { - User user = userService.getUsersMail(Hellohao_UniqueUserKey); - if (user.getIsok() == 1) { - httpSession.setAttribute("user", user); - httpSession.setAttribute("email", user.getEmail()); - jsonArray.add(1); - } else if(ret==-1){ - jsonArray.add(-1); - }else { - jsonArray.add(-2); - } - } else { - jsonArray.add(0); - } - return jsonArray.toString(); + return msg; } //退出 - @RequestMapping(value = "/exit.do") + @PostMapping(value = "/logout") @ResponseBody - public String exit(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { - JSONObject jsonObject = new JSONObject(); - Cookie[] cookies = request.getCookies(); - if(cookies!=null){ - for (Cookie cookie : cookies) { - Cookie c = null; - cookie.setPath("/"); - if(cookie.getName().equals("Hellohao_UniqueUserKey")){ - //cookie.setValue(null); - c = new Cookie("Hellohao_UniqueUserKey",""); - c.setPath("/"); - cookie.setMaxAge(0);//60*60*24*90 - response.addCookie(c); - } - } - } - //注销,移除session - User user = (User) session.getAttribute("user"); - if (user.getEmail() != null && user.getPassword() != null) { - session.removeAttribute(user.getEmail()); - session.removeAttribute(user.getPassword()); - session.removeAttribute("user"); - } - //刷新view - session.invalidate(); - jsonObject.put("exit", 1); + public Msg exit(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { + Msg msg = new Msg(); + Subject subject = SecurityUtils.getSubject(); + subject.logout(); + msg.setInfo("退出成功"); + Print.Normal("用户账号退出成功"); + return msg; + } - return jsonObject.toString(); + @PostMapping("/retrievePass") + @ResponseBody + public Msg retrievePass(HttpServletRequest request, @RequestParam(value = "data", defaultValue = "") String data) { + Msg msg = new Msg(); + try { + JSONObject jsonObj = JSONObject.parseObject(data); + String email = jsonObj.getString("email"); + String retrieveCode = jsonObj.getString("retrieveCode"); + String userIP = GetIPS.getIpAddr(request); + Object redis_verifyCodeForEmailRetrieve = iRedisService.getValue(userIP+"_hellohao_verifyCodeForEmailRetrieve"); + EmailConfig emailConfig = emailConfigService.getemail(); + if(null==redis_verifyCodeForEmailRetrieve){ + msg.setCode("4035"); + msg.setInfo("验证码已失效,请重新弄获取。"); + return msg; + }else if(null==retrieveCode){ + msg.setCode("4036"); + msg.setInfo("验证码不能为空。"); + return msg; + } + if((redis_verifyCodeForEmailRetrieve.toString().toLowerCase()).compareTo((retrieveCode.toLowerCase()))!=0){ + msg.setCode("40034"); + msg.setInfo("验证码不正确"); + return msg; + } + + Integer ret = userService.countmail(email); + if(ret>0){ + if(emailConfig.getUsing()==1){ + User u2 = new User(); + u2.setEmail(email); + User user = userService.getUsers(u2); + if(user.getIsok()==-1){ + msg.setCode("110110"); + msg.setInfo("当前用户已被冻结,禁止操作"); + return msg; + } + Config config = configService.getSourceype(); + Thread thread = new Thread() { + public void run() { + Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),config);//SendEmail.sendEmailT(message, user.getUsername(), user.getUid(), user.getEmail(),emailConfig,config); + } + }; + thread.start(); + msg.setInfo("重置密码的验证链接已发送至该邮箱,请前往邮箱验证并重置密码。【若长时间未收到邮件,请检查垃圾箱】"); + }else{ + msg.setCode("400"); + msg.setInfo("本站暂未开启邮箱服务,请联系管理员"); + } + }else{ + msg.setCode("110404"); + msg.setInfo("未找到邮箱所在的用户"); + } + }catch (Exception e){ + e.printStackTrace(); + msg.setCode("110500"); + msg.setInfo("系统发生错误"); + } + return msg; } //邮箱激活 - @RequestMapping(value = "/activation.do", method = RequestMethod.GET) + @RequestMapping(value = "/activation", method = RequestMethod.GET) public String activation(Model model, HttpServletRequest request, HttpSession session, String activation, String username) { Config config = configService.getSourceype(); Integer ret = 0; - User user = userService.getUsersMail(activation); - model.addAttribute("config", config); + User u2 = new User(); + u2.setUid(activation); + User user = userService.getUsers(u2); + model.addAttribute("webhost", SubjectFilter.WEBHOST); if (user != null && user.getIsok() == 0) { - Integer setisok = userService.uiduser(activation); - model.addAttribute("setisok", ret); - model.addAttribute("username", username); - return "isok"; + userService.uiduser(activation); + model.addAttribute("title","激活成功"); + model.addAttribute("name","Hi~"+username); + model.addAttribute("note","您的账号已成功激活看"); + return "msg"; } else { - return "redirect:/index"; + model.addAttribute("title","操作无效"); + model.addAttribute("name","该页面为无效页面"); + model.addAttribute("note","请返回首页"); + return "msg"; } + } @PostMapping(value = "/verification") @ResponseBody diff --git a/src/main/java/cn/hellohao/dao/AlbumMapper.java b/src/main/java/cn/hellohao/dao/AlbumMapper.java index 2cd8b51..3dd173b 100644 --- a/src/main/java/cn/hellohao/dao/AlbumMapper.java +++ b/src/main/java/cn/hellohao/dao/AlbumMapper.java @@ -4,7 +4,6 @@ import cn.hellohao.pojo.Album; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; -import javax.validation.constraints.Max; import java.util.List; /** @@ -22,4 +21,6 @@ public interface AlbumMapper { Integer deleteAlbum(@Param("albumkey") String albumkey); List selectAlbumURLList(Album album); + + Integer selectAlbumCount(@Param("userid") Integer userid); } diff --git a/src/main/java/cn/hellohao/dao/GroupMapper.java b/src/main/java/cn/hellohao/dao/GroupMapper.java index be373bd..b306ed0 100644 --- a/src/main/java/cn/hellohao/dao/GroupMapper.java +++ b/src/main/java/cn/hellohao/dao/GroupMapper.java @@ -16,6 +16,8 @@ public interface GroupMapper { List grouplist(); Group idgrouplist(@Param("id") Integer id); Integer addgroup(Group group); + Integer GetCountFroUserType(@Param("usertype") Integer usertype); Integer delegroup(@Param("id") Integer id); Integer setgroup(Group group); + Group getGroupFroUserType(@Param("usertype") Integer usertype); } diff --git a/src/main/java/cn/hellohao/dao/ImgMapper.java b/src/main/java/cn/hellohao/dao/ImgMapper.java index cf66f10..8450c27 100644 --- a/src/main/java/cn/hellohao/dao/ImgMapper.java +++ b/src/main/java/cn/hellohao/dao/ImgMapper.java @@ -2,6 +2,7 @@ package cn.hellohao.dao; import java.util.List; +import cn.hellohao.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -27,11 +28,21 @@ public interface ImgMapper { List gettimeimg(@Param("time") String time); - Integer getusermemory(@Param("userid") Integer userid); + Long getusermemory(@Param("userid") Integer userid); Integer md5Count(@Param("md5key") String md5key); Images selectImgUrlByMD5(@Param("md5key") String md5key); + List RecentlyUploaded(@Param("userid") Integer userid); + + List RecentlyUser(); + + Integer addGreat(@Param("id") Integer id); + + List getyyyy(@Param("userid") Integer userid); + + List countByM(Images images); + } diff --git a/src/main/java/cn/hellohao/dao/ImgTempMapper.java b/src/main/java/cn/hellohao/dao/ImgTempMapper.java new file mode 100644 index 0000000..aa1da74 --- /dev/null +++ b/src/main/java/cn/hellohao/dao/ImgTempMapper.java @@ -0,0 +1,20 @@ +package cn.hellohao.dao; + +import cn.hellohao.pojo.Images; +import cn.hellohao.pojo.ImgTemp; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** +* @Entity dao.pojo.Imgdataexp +*/ +@Mapper +public interface ImgTempMapper { + + List selectDelImgUidList(@Param("datatime") String datatime); + Integer delImgAndExp(@Param("imguid") String imguid); + Integer insertImgExp(ImgTemp imgDataExp); + +} diff --git a/src/main/java/cn/hellohao/dao/ImgreviewMapper.java b/src/main/java/cn/hellohao/dao/ImgreviewMapper.java index 30d22fc..ea7638d 100644 --- a/src/main/java/cn/hellohao/dao/ImgreviewMapper.java +++ b/src/main/java/cn/hellohao/dao/ImgreviewMapper.java @@ -2,6 +2,7 @@ package cn.hellohao.dao; import cn.hellohao.pojo.Imgreview; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; @Mapper public interface ImgreviewMapper { @@ -11,7 +12,9 @@ public interface ImgreviewMapper { int insertSelective(Imgreview record); - Imgreview selectByPrimaryKey(Integer id); + Imgreview selectByPrimaryKey(@Param("id") Integer id); + + Imgreview selectByusing(@Param("using") Integer using); int updateByPrimaryKeySelective(Imgreview record); diff --git a/src/main/java/cn/hellohao/dao/KeysMapper.java b/src/main/java/cn/hellohao/dao/KeysMapper.java index d1509d1..e4e76af 100644 --- a/src/main/java/cn/hellohao/dao/KeysMapper.java +++ b/src/main/java/cn/hellohao/dao/KeysMapper.java @@ -10,7 +10,7 @@ import java.util.List; @Mapper public interface KeysMapper { //查询密钥 - Keys selectKeys(@Param("storageType") Integer storageType); + Keys selectKeys(@Param("id") Integer id); //修改key Integer updateKey(Keys key); List getKeys(); diff --git a/src/main/java/cn/hellohao/dao/UserMapper.java b/src/main/java/cn/hellohao/dao/UserMapper.java index 6a4f831..57a337d 100644 --- a/src/main/java/cn/hellohao/dao/UserMapper.java +++ b/src/main/java/cn/hellohao/dao/UserMapper.java @@ -17,7 +17,7 @@ public interface UserMapper { Integer login(@Param("email") String email, @Param("password") String password,@Param("uid") String uid); //获取用户信息 - User getUsers(@Param("email") String email); + User getUsers(User user); //插入图片 Integer insertimg(Images img); diff --git a/src/main/java/cn/hellohao/interceptor/InterceptorConfig.java b/src/main/java/cn/hellohao/interceptor/InterceptorConfig.java deleted file mode 100644 index bde5d08..0000000 --- a/src/main/java/cn/hellohao/interceptor/InterceptorConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package cn.hellohao.interceptor; - -import java.io.PrintWriter; -import java.net.URLDecoder; -import java.net.URLEncoder; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import cn.hellohao.pojo.User; -import cn.hellohao.service.impl.NOSImageupload; -import cn.hellohao.service.impl.UserServiceImpl; -import cn.hellohao.utils.Base64Encryption; -import cn.hellohao.utils.Print; -import cn.hellohao.utils.SpringContextHolder; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - - -@Component -public class InterceptorConfig implements HandlerInterceptor { - - /** - * 进入controller层之前拦截请求 - */ - //这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,就可以在用户调用指定接口之前验证登陆状态了 - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - UserServiceImpl userService = SpringContextHolder.getBean(UserServiceImpl.class); - HttpSession session = request.getSession(); - User suser = (User) session.getAttribute("user"); - String email = null; - Integer level = 0; - if (suser != null) { - email = suser.getEmail(); - level = suser.getLevel(); - } - if (email == null) { - //这个方法返回false表示忽略当前请求,如果一个用户调用了需要登陆才能使用的接口,如果他没有登陆这里会直接忽略掉 - //当然你可以利用response给用户返回一些提示信息,告诉他没登陆 - System.out.println("没有登录权限"); - request.getRequestDispatcher("/err").forward(request, response); - return false; - } else { - //System.out.println("进入成功"); - return true; //如果session里有user,表示该用户已经登陆,放行,用户即可继续调用自己需要的接口 - } - } - - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { - } - - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { - } - -} diff --git a/src/main/java/cn/hellohao/interceptor/InterceptorConfigTwo.java b/src/main/java/cn/hellohao/interceptor/InterceptorConfigTwo.java deleted file mode 100644 index b9c0504..0000000 --- a/src/main/java/cn/hellohao/interceptor/InterceptorConfigTwo.java +++ /dev/null @@ -1,59 +0,0 @@ -package cn.hellohao.interceptor; - -import cn.hellohao.pojo.User; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - - -@Component -public class InterceptorConfigTwo implements HandlerInterceptor { - //private static final Logger log = LoggerFactory.getLogger(InterceptorConfig.class); - - /** - * 进入controller层之前拦截请求 - */ - //这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,就可以在用户调用指定接口之前验证登陆状态了 - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - - //每一个项目对于登陆的实现逻辑都有所区别,我这里使用最简单的Session提取User来验证登陆。 - HttpSession session = request.getSession(); - //这里的User是登陆时放入session的 - User user = (User) session.getAttribute("user"); - String email = null; - Integer level = 0; - if (user != null) { - email = user.getEmail(); - level = user.getLevel(); - } - // String email = (String) session.getAttribute("email"); - //如果session中没有user,表示没登陆 - if (email == null) { - //这个方法返回false表示忽略当前请求,如果一个用户调用了需要登陆才能使用的接口,如果他没有登陆这里会直接忽略掉 - //当然你可以利用response给用户返回一些提示信息,告诉他没登陆 - System.out.println("没有登录权限"); - request.getRequestDispatcher("/index").forward(request, response); - return false; - } else { - if (level == 2) { - System.out.println("进入成功"); - return true; //如果session里有user,表示该用户已经登陆,放行,用户即可继续调用自己需要的接口 - } else { - request.getRequestDispatcher("/admin/admin").forward(request, response); - return false; - } - } - } - - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { - } - - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { - } - -} diff --git a/src/main/java/cn/hellohao/interceptor/InterceptorConfigWeb.java b/src/main/java/cn/hellohao/interceptor/InterceptorConfigWeb.java deleted file mode 100644 index ea0725b..0000000 --- a/src/main/java/cn/hellohao/interceptor/InterceptorConfigWeb.java +++ /dev/null @@ -1,72 +0,0 @@ -package cn.hellohao.interceptor; - -import cn.hellohao.pojo.User; -import cn.hellohao.service.impl.UserServiceImpl; -import cn.hellohao.utils.SpringContextHolder; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.net.URLDecoder; -import java.util.Date; - - -@Component -public class InterceptorConfigWeb implements HandlerInterceptor { - //private static final Logger log = LoggerFactory.getLogger(InterceptorConfig.class); - - /** - * 进入controller层之前拦截请求 - */ - //这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,就可以在用户调用指定接口之前验证登陆状态了 - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //设置请求头 - response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); - response.setHeader("Pragma", "no-cache"); - response.setHeader("Expires", "0"); - response.setHeader("Last-Modified", new Date().toString()); - response.setHeader("ETag", String.valueOf(System.currentTimeMillis())); - - UserServiceImpl userService = SpringContextHolder.getBean(UserServiceImpl.class); - HttpSession session = request.getSession(); - //这里的User是登陆时放入session的 - User user = (User) session.getAttribute("user"); - if(user==null){ - Cookie[] cookies = request.getCookies(); - String Hellohao_UniqueUserKey = ""; - if(cookies!=null){ - for (Cookie cookie : cookies) { - if(cookie.getName().equals("Hellohao_UniqueUserKey") && Hellohao_UniqueUserKey.equals("")){ - Hellohao_UniqueUserKey = URLDecoder.decode(cookie.getValue(), "GBK"); - } - } - } - if(Hellohao_UniqueUserKey!=null && !Hellohao_UniqueUserKey.equals("")){ - //String basepass = Base64Encryption.encryptBASE64(pass.getBytes()); - Integer ret = userService.login(null, null,Hellohao_UniqueUserKey); - if (ret > 0) { - User u = userService.getUsersMail(Hellohao_UniqueUserKey); - if (u.getIsok() == 1) { - session.setAttribute("user", u); - session.setAttribute("email", u.getEmail()); - //request.getRequestDispatcher("/admin/goadmin").forward(request, response); - } - } - } - } - - return true; - } - - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { - } - - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { - } - -} diff --git a/src/main/java/cn/hellohao/interceptor/WebAppConfig.java b/src/main/java/cn/hellohao/interceptor/WebAppConfig.java deleted file mode 100644 index f736539..0000000 --- a/src/main/java/cn/hellohao/interceptor/WebAppConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package cn.hellohao.interceptor; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - - - -@Configuration -public class WebAppConfig implements WebMvcConfigurer { - - - @Autowired - private InterceptorConfig interceptorConfig; - @Autowired - private InterceptorConfigTwo interceptorConfigTwo; - @Autowired - private InterceptorConfigWeb interceptorConfigWeb; - - - // 这个方法是用来配置静态资源的,比如html,js,css,等等 - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - } - - // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效 - @Override - public void addInterceptors(InterceptorRegistry registry) { - // addPathPatterns("/**") 表示拦截所有的请求, - // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问 - //registry.addInterceptor(interceptorConfig).addPathPatterns("admin/**").excludePathPatterns("/login", "/register"); - registry.addInterceptor(interceptorConfigWeb).addPathPatterns("/**") - .excludePathPatterns("/static/**","/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", - "/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg","/**/*.*", - "/clientupimg/**","/clientupurlimg/**","/clientlogin/**","/notices/**","/systemupdate/**","/getdomain/**", - "/getNoticeText/**","/getNotice/**","/addalbum/**","/addalbum/**","/SaveForAlbum/**","/TOALBUM*N/**","/TOALBUM*N/**"); - registry.addInterceptor(interceptorConfig).addPathPatterns("/admin/**").excludePathPatterns("/**/*.*"); - registry.addInterceptor(interceptorConfigTwo).addPathPatterns("/admin/root/**").excludePathPatterns("/**/*.*"); - - - - } - -} diff --git a/src/main/java/cn/hellohao/pojo/Config.java b/src/main/java/cn/hellohao/pojo/Config.java index 0d5ebec..3fe1c29 100644 --- a/src/main/java/cn/hellohao/pojo/Config.java +++ b/src/main/java/cn/hellohao/pojo/Config.java @@ -19,11 +19,16 @@ public class Config { private String webkeywords; private String webfavicons; private Integer theme; + private String websubtitle; + private String logo; + private String aboutinfo; public Config() { } - public Config(Integer id, Integer sourcekey, Integer emails, String webname, String explain, String video, Integer backtype, String links, String notice, String baidu, String domain, String background1, String background2, String sett, String webms, String webkeywords, String webfavicons, Integer theme) { + 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; @@ -42,6 +47,10 @@ public class Config { this.webkeywords = webkeywords; this.webfavicons = webfavicons; this.theme = theme; + this.websubtitle = websubtitle; + this.logo = logo; + this.aboutinfo = aboutinfo; + } public Integer getId() { @@ -187,4 +196,28 @@ public class Config { 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; + } } diff --git a/src/main/java/cn/hellohao/pojo/Images.java b/src/main/java/cn/hellohao/pojo/Images.java index 0de666b..7086bdb 100644 --- a/src/main/java/cn/hellohao/pojo/Images.java +++ b/src/main/java/cn/hellohao/pojo/Images.java @@ -1,11 +1,5 @@ package cn.hellohao.pojo; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.hibernate.validator.constraints.Length; - -import javax.validation.constraints.NotBlank; - public class Images { // 默认的时间字符串格式 @@ -14,7 +8,7 @@ public class Images { private String imgname; private String imgurl; private Integer userid; - private Integer sizes = 0; + private String sizes; private String abnormal; private Integer source; private Integer imgtype; @@ -23,23 +17,45 @@ public class Images { private Integer storageType; private String starttime; private String stoptime; - @Length(min = 1, max = 100, message = "图片描述不得超过100个字符") private String explains; private String md5key; - //Album - @NotBlank(message = "画廊标题不能为空") - @Length(min = 1, max = 50, message = "画廊标题不得超过50个字符") + private String notes; + private String useridlist; + private String imguid; + private String shortlink; + private String format; + private String about; + private Integer great; + private String violation; private String albumtitle; - @Length(min = 0, max = 10, message = "画廊密码不能超过10个字符") + //@Length(min = 0, max = 10, message = "画廊密码不能超过10个字符") private String password; private Integer selecttype; - private String notes; + private Long countNum; + private Integer monthNum; + private String yyyy; + private String[] classifuidlist; //类别uid集合 + private String classificationuid; //类别uid集合 public Images() { super(); } - public Images(Integer id, String imgname, String imgurl, Integer userid, Integer sizes, String abnormal, Integer source, Integer imgtype, String updatetime, String username, Integer storageType, String starttime, String stoptime, @Length(min = 1, max = 100, message = "图片描述不得超过100个字符") String explains, String md5key, String albumtitle,String password, Integer selecttype, String notes) { + public Images(String imgurl, String sizes, String abnormal, String updatetime, String username, String md5key, String imguid,String shortlink) { + this.imgurl = imgurl; + this.sizes = sizes; + this.abnormal = abnormal; + this.updatetime = updatetime; + this.username = username; + this.md5key = md5key; + this.imguid = imguid; + } + + public Images(Integer id, String imgname, String imgurl, Integer userid, String sizes, String abnormal, Integer source, + Integer imgtype, String updatetime, String username, Integer storageType, String starttime, String stoptime, + String explains, String md5key, String notes, String useridlist, String imguid, String albumtitle, + String password, Integer selecttype,Long countNum,Integer monthNum,String yyyy,String shortlink, + String format,String about,Integer great,String[] classifuidlist,String classificationuid,String violation) { this.id = id; this.imgname = imgname; this.imgurl = imgurl; @@ -55,10 +71,23 @@ public class Images { this.stoptime = stoptime; this.explains = explains; this.md5key = md5key; + this.notes = notes; + this.useridlist = useridlist; + this.imguid = imguid; + this.shortlink = shortlink; this.albumtitle = albumtitle; this.password = password; this.selecttype = selecttype; - this.notes = notes; + this.countNum = countNum; + this.monthNum = monthNum; + this.yyyy = yyyy; + this.format = format; + this.about = about; + this.great = great; + this.classifuidlist = classifuidlist; + this.classificationuid = classificationuid; + this.violation = violation; + } public Integer getId() { @@ -93,11 +122,11 @@ public class Images { this.userid = userid; } - public Integer getSizes() { + public String getSizes() { return sizes; } - public void setSizes(Integer sizes) { + public void setSizes(String sizes) { this.sizes = sizes; } @@ -181,6 +210,38 @@ public class Images { this.md5key = md5key; } + public String getNotes() { + return notes; + } + + public void setNotes(String notes) { + this.notes = notes; + } + + public String getUseridlist() { + return useridlist; + } + + public void setUseridlist(String useridlist) { + this.useridlist = useridlist; + } + + public String getImguid() { + return imguid; + } + + public void setImguid(String imguid) { + this.imguid = imguid; + } + + public String getShortlink() { + return shortlink; + } + + public void setShortlink(String shortlink) { + this.shortlink = shortlink; + } + public String getAlbumtitle() { return albumtitle; } @@ -205,12 +266,76 @@ public class Images { this.selecttype = selecttype; } - public String getNotes() { - return notes; + public Long getCountNum() { + return countNum; } - public void setNotes(String notes) { - this.notes = notes; + public void setCountNum(Long countNum) { + this.countNum = countNum; + } + + public Integer getMonthNum() { + return monthNum; + } + + public void setMonthNum(Integer monthNum) { + this.monthNum = monthNum; + } + + public String getYyyy() { + return yyyy; + } + + public void setYyyy(String yyyy) { + this.yyyy = yyyy; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public String getAbout() { + return about; + } + + public void setAbout(String about) { + this.about = about; + } + + public Integer getGreat() { + return great; + } + + public void setGreat(Integer great) { + this.great = great; + } + + public String[] getClassifuidlist() { + return classifuidlist; + } + + public void setClassifuidlist(String[] classifuidlist ) { + this.classifuidlist = classifuidlist; + } + + public String getClassificationuid() { + return classificationuid; + } + + public void setClassificationuid(String classificationuid) { + this.classificationuid = classificationuid; + } + + public String getViolation() { + return violation; + } + + public void setViolation(String violation) { + this.violation = violation; } } diff --git a/src/main/java/cn/hellohao/pojo/ImgTemp.java b/src/main/java/cn/hellohao/pojo/ImgTemp.java new file mode 100644 index 0000000..514a1a5 --- /dev/null +++ b/src/main/java/cn/hellohao/pojo/ImgTemp.java @@ -0,0 +1,66 @@ +package cn.hellohao.pojo; + +/** + * By Hellohao + * @TableName ImgTemp + */ +public class ImgTemp { + /** + * + */ + private Integer id; + + /** + * + */ + private String imguid; + + + /** + * + */ + private String deltime; + + public ImgTemp() { + } + + public ImgTemp(Integer id, String imguid, String deltime) { + this.id = id; + this.imguid = imguid; + this.deltime = deltime; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getImguid() { + return imguid; + } + + public void setImguid(String imguid) { + this.imguid = imguid; + } + + public String getDeltime() { + return deltime; + } + + public void setDeltime(String deltime) { + this.deltime = deltime; + } + + + @Override + public String toString() { + return "ImgTemp{" + + "id=" + id + + ", imguid='" + imguid + '\'' + + ", deltime='" + deltime + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/pojo/ReturnImage.java b/src/main/java/cn/hellohao/pojo/ReturnImage.java index bf55dff..19dadb4 100644 --- a/src/main/java/cn/hellohao/pojo/ReturnImage.java +++ b/src/main/java/cn/hellohao/pojo/ReturnImage.java @@ -3,18 +3,40 @@ package cn.hellohao.pojo; /** * @author Hellohao * @version 1.0 - * @date 2019-07-22 11:35 + * @date 2021-10-22 11:35 */ public class ReturnImage { + private String uid; + private String code; private String imgurl; private String imgname; + private Long imgSize; public ReturnImage() { } - public ReturnImage(String imgurl, String imgname) { + public ReturnImage(String uid,String code, String imgurl, String imgname, Long imgSize) { + this.uid = uid; + this.code = code; this.imgurl = imgurl; this.imgname = imgname; + this.imgSize = imgSize; + } + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; } public String getImgurl() { @@ -32,4 +54,13 @@ public class ReturnImage { public void setImgname(String imgname) { this.imgname = imgname; } + + public Long getImgSize() { + return imgSize; + } + + public void setImgSize(Long imgSize) { + this.imgSize = imgSize; + } + } diff --git a/src/main/java/cn/hellohao/pojo/User.java b/src/main/java/cn/hellohao/pojo/User.java index afa502a..e690d1a 100644 --- a/src/main/java/cn/hellohao/pojo/User.java +++ b/src/main/java/cn/hellohao/pojo/User.java @@ -1,9 +1,5 @@ package cn.hellohao.pojo; -import org.hibernate.validator.constraints.Length; - -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; public class User { diff --git a/src/main/java/cn/hellohao/quartz/QuartzConfigration.java b/src/main/java/cn/hellohao/quartz/QuartzConfigration.java index 6c609bb..56ee8ab 100644 --- a/src/main/java/cn/hellohao/quartz/QuartzConfigration.java +++ b/src/main/java/cn/hellohao/quartz/QuartzConfigration.java @@ -17,8 +17,8 @@ import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; @Configuration public class QuartzConfigration { //直接读取properties文件的值 - @Value("${Expression}") - private String Expression; +// @Value("${Expression}") + private String Expression = "0 0 1 1 * ?"; diff --git a/src/main/java/cn/hellohao/service/AlbumService.java b/src/main/java/cn/hellohao/service/AlbumService.java index fd9a7d6..cdbf0b4 100644 --- a/src/main/java/cn/hellohao/service/AlbumService.java +++ b/src/main/java/cn/hellohao/service/AlbumService.java @@ -21,4 +21,6 @@ public interface AlbumService { Integer deleteAlbum(String albumkey); List selectAlbumURLList(Album album); + + Integer selectAlbumCount(Integer userid); } diff --git a/src/main/java/cn/hellohao/service/GroupService.java b/src/main/java/cn/hellohao/service/GroupService.java index 3f48c67..d699102 100644 --- a/src/main/java/cn/hellohao/service/GroupService.java +++ b/src/main/java/cn/hellohao/service/GroupService.java @@ -15,6 +15,8 @@ public interface GroupService { List grouplist(); Group idgrouplist(Integer id); Integer addgroup(Group group); + Integer GetCountFroUserType(Integer usertype); Integer delegroup(Integer id); Integer setgroup(Group group); + Group getGroupFroUserType(Integer usertype); } diff --git a/src/main/java/cn/hellohao/service/IRedisService.java b/src/main/java/cn/hellohao/service/IRedisService.java new file mode 100644 index 0000000..2e9a374 --- /dev/null +++ b/src/main/java/cn/hellohao/service/IRedisService.java @@ -0,0 +1,17 @@ +package cn.hellohao.service; + +import java.util.Map; + +public interface IRedisService { + + // 加入元素 + void setValue(String key, Map value); + // 加入元素 + void setValue(String key, String value); + // 加入元素 + void setValue(String key, Object value); + // 获取元素 + Object getMapValue(String key); + // 获取元素 + Object getValue(String key); +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/service/ImgService.java b/src/main/java/cn/hellohao/service/ImgService.java index 338be78..008a04e 100644 --- a/src/main/java/cn/hellohao/service/ImgService.java +++ b/src/main/java/cn/hellohao/service/ImgService.java @@ -3,6 +3,7 @@ package cn.hellohao.service; import java.util.List; +import cn.hellohao.pojo.User; import org.apache.ibatis.annotations.Param; import cn.hellohao.pojo.Images; @@ -28,10 +29,20 @@ public interface ImgService { List gettimeimg(String time); - Integer getusermemory(Integer userid); + Long getusermemory(Integer userid); Integer md5Count(String md5key); Images selectImgUrlByMD5(String md5key); + List RecentlyUploaded(Integer userid); + + List RecentlyUser(); + + Integer addGreat(Integer id); + + List getyyyy(Integer userid); + + List countByM(Images images); + } diff --git a/src/main/java/cn/hellohao/service/ImgTempService.java b/src/main/java/cn/hellohao/service/ImgTempService.java new file mode 100644 index 0000000..71ea7d1 --- /dev/null +++ b/src/main/java/cn/hellohao/service/ImgTempService.java @@ -0,0 +1,17 @@ +package cn.hellohao.service; + +import cn.hellohao.pojo.Images; +import cn.hellohao.pojo.ImgTemp; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** +* +*/ +@Service +public interface ImgTempService { + List selectDelImgUidList(String datatime); + Integer delImgAndExp(String imguid); + Integer insertImgExp(ImgTemp imgDataExp); +} diff --git a/src/main/java/cn/hellohao/service/ImgreviewService.java b/src/main/java/cn/hellohao/service/ImgreviewService.java index f665556..115873d 100644 --- a/src/main/java/cn/hellohao/service/ImgreviewService.java +++ b/src/main/java/cn/hellohao/service/ImgreviewService.java @@ -17,4 +17,6 @@ public interface ImgreviewService { int updateByPrimaryKey(Imgreview record); + Imgreview selectByusing(Integer using); + } diff --git a/src/main/java/cn/hellohao/service/KeysService.java b/src/main/java/cn/hellohao/service/KeysService.java index 177ece2..8407a5b 100644 --- a/src/main/java/cn/hellohao/service/KeysService.java +++ b/src/main/java/cn/hellohao/service/KeysService.java @@ -9,7 +9,7 @@ import java.util.List; @Service public interface KeysService { //查询密钥 - Keys selectKeys(Integer storageType); + Keys selectKeys(Integer id); //修改key Integer updateKey(Keys key); diff --git a/src/main/java/cn/hellohao/service/UserService.java b/src/main/java/cn/hellohao/service/UserService.java index 031e29a..4869b8c 100644 --- a/src/main/java/cn/hellohao/service/UserService.java +++ b/src/main/java/cn/hellohao/service/UserService.java @@ -16,7 +16,7 @@ public interface UserService { Integer login(String email, String password,String uid); //获取用户信息 - User getUsers(String email); + User getUsers(User user); //插入图片 Integer insertimg(Images img); diff --git a/src/main/java/cn/hellohao/service/impl/AlbumServiceI.java b/src/main/java/cn/hellohao/service/impl/AlbumServiceI.java index 71049af..1659649 100644 --- a/src/main/java/cn/hellohao/service/impl/AlbumServiceI.java +++ b/src/main/java/cn/hellohao/service/impl/AlbumServiceI.java @@ -62,6 +62,11 @@ public class AlbumServiceI implements AlbumService { return albumMapper.selectAlbumURLList(album); } + @Override + public Integer selectAlbumCount(Integer userid) { + return albumMapper.selectAlbumCount(userid); + } + @Transactional public Integer delete(String albumkey) { Integer ret1 = albumMapper.deleteAlbum(albumkey); diff --git a/src/main/java/cn/hellohao/service/impl/COSImageupload.java b/src/main/java/cn/hellohao/service/impl/COSImageupload.java index 085bd86..dacd019 100644 --- a/src/main/java/cn/hellohao/service/impl/COSImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/COSImageupload.java @@ -26,87 +26,38 @@ import java.util.*; @Service public class COSImageupload { - static String BarrelName; static COSClient cosClient; static Keys key; - public Map ImageuploadCOS(Map fileMap, String username, - Map fileMap2,Integer setday) { - // 要上传文件的路径 - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - try { - // 指定要上传到的存储桶 - String bucketName = BarrelName; - // 指定要上传到 COS 上对象键 - String userkey =username + "/" + uuid+times + "." + entry.getKey(); - PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, userkey, file); - PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(userkey);//entry.getValue().getOriginalFilename() - returnImage.setImgurl(key.getRequestAddress() + "/" + userkey); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "6"); - } - } catch (CosServiceException serverException) { - serverException.printStackTrace(); - } catch (CosClientException clientException) { - clientException.printStackTrace(); - } + public ReturnImage ImageuploadCOS(Map fileMap, String username,Integer keyID) { + ReturnImage returnImage = new ReturnImage(); + File file = null; + Map ImgUrl = new HashMap<>(); + try { + for (Map.Entry entry : fileMap.entrySet()) { + String ShortUID = SetText.getShortUuid(); + file = entry.getValue(); + try { + String bucketName = key.getBucketname(); + String userkey =username + "/" + ShortUID + "." + entry.getKey(); + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, userkey, file); + PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); + returnImage.setUid(ShortUID); + returnImage.setImgname(userkey); + returnImage.setImgurl(key.getRequestAddress() + "/" + userkey); + returnImage.setImgSize(entry.getValue().length()); + returnImage.setCode("200"); + } catch (CosServiceException serverException) { + serverException.printStackTrace(); + } catch (CosClientException clientException) { + clientException.printStackTrace(); } - }catch(Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - File file = new File(imgurl); - FileInputStream fileInputStream = new FileInputStream(file); - try { - String userkey =username + "/" + uuid+times + "." + entry.getKey(); - PutObjectRequest putObjectRequest = new PutObjectRequest(BarrelName, userkey, file); - PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + "/" + userkey); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "6"); - } - boolean bb= new File(imgurl).getAbsoluteFile().delete(); - Print.Normal("删除情况"+bb); - } catch (Exception e) { - System.err.println("上传报错:" + e.getMessage()); - } - if(fileInputStream!=null){ - fileInputStream.close(); - Print.Normal("流已经关闭"); - } - } - }catch(Exception e){ - ImgUrl.put(null, 500); - } - cosClient.shutdown(); - return ImgUrl; + }catch(Exception e){ + e.printStackTrace(); + returnImage.setCode("200"); } + return returnImage; } @@ -121,9 +72,7 @@ public class COSImageupload { COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); Region region = new Region(k.getEndpoint()); ClientConfig clientConfig = new ClientConfig(region); - cosClient = new COSClient(cred, clientConfig); - BarrelName = k.getBucketname(); - + COSClient cosClient = new COSClient(cred, clientConfig); ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); listObjectsRequest.setBucketName(k.getBucketname()); listObjectsRequest.setDelimiter("/"); @@ -131,49 +80,30 @@ public class COSImageupload { ObjectListing objectListing = null; try { objectListing = cosClient.listObjects(listObjectsRequest); - key = k; ret = 1; + cosClient = cosClient; + key = k; } catch (Exception e) { - System.out.println("COS - Waiting for configuration。"); + System.out.println("COS Object Is null"); ret = -1; } } } return ret; } - /** - * 客户端接口 - * */ - public Map clientuploadCOS(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - File file = null; - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - try { - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - String userkey =username + "/" + uuid+times + "." + entry.getKey(); - PutObjectRequest putObjectRequest = new PutObjectRequest(BarrelName, userkey, file); - PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + "/" + userkey); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - } - } catch (Exception e) { - System.err.println("上传报错:" + e.getMessage()); - } + public Boolean delCOS(Integer keyID, String fileName) { + boolean b = true; + try { + cosClient.deleteObject(key.getBucketname(), fileName); + } catch (Exception e) { + e.printStackTrace(); + b = false; } - return ImgUrl; - + return b ; } + + } diff --git a/src/main/java/cn/hellohao/service/impl/FTPImageupload.java b/src/main/java/cn/hellohao/service/impl/FTPImageupload.java index 788589c..3ce56f3 100644 --- a/src/main/java/cn/hellohao/service/impl/FTPImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/FTPImageupload.java @@ -20,76 +20,43 @@ public class FTPImageupload { static FTPClient ftpClient1 ; static Keys key; - public Map ImageuploadFTP(Map fileMap, String username, - Map fileMap2,Integer setday) { + public ReturnImage ImageuploadFTP(Map 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]); - //创建FTP客户端,所有的操作都基于FTPClinet FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret()); boolean flag = ftps.open(); - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - ftps.mkDir(File.separator+username); - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - String userkey =username + "/"+ uuid+times + "." + entry.getKey(); - if (flag) { - ftps.upload(file, "/"+userkey, ""); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(userkey);//entry.getValue().getOriginalFilename() + File file = null; + Map ImgUrl = new HashMap<>(); + ftps.mkDir(File.separator+username); + try { + for (Map.Entry 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.setUid(ShortUID); + returnImage.setImgname(userkey); returnImage.setImgurl(key.getRequestAddress() + "/"+ userkey); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "7"); - } - ftps.close(); + returnImage.setImgSize(entry.getValue().length()); + returnImage.setCode("200"); + }else{ + returnImage.setCode("500"); } - - Print.Normal("要上传的文件路径:"+"/"+userkey); } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); + Print.Normal("要上传的文件路径:/"+userkey); } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - File file = new File(imgurl); - String userkey =username + File.separator+ uuid+times + "." + entry.getKey(); - ftps.mkDir(File.separator+username); - if (flag) { - ftps.upload(file, "/"+userkey, ""); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "7"); - } - ftps.close(); - } - boolean bb= new File(imgurl).getAbsoluteFile().delete(); - Print.Normal("删除情况"+bb); - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); - } - return ImgUrl; + }catch (Exception e){ + e.printStackTrace(); + returnImage.setCode("500"); +// ImgUrl.put(null, 500); } + return returnImage; + } //初始化FTP对象存储 @@ -98,85 +65,38 @@ public class FTPImageupload { 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(); - /* - * 判断是否连接成功 - * 所有以2开头的代码是正完成响应。 - * FTP服务器将在最终发送一个肯定的完成响应成功完成命令。 - */ - if (!FTPReply.isPositiveCompletion(reply)) { - System.out.println("FTP - Waiting for configuration"); - ftp.disconnect(); - return -1; - } - ftpClient1 = ftp; - key = k; - ret = 1; - // if(ftp.printWorkingDirectory()==null){ - // Print.warning("FTP初始化失败,配置项错误"); - // return -1; - // } - } catch (IOException e) { - System.out.println("FTP - Waiting for configuration"); + 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; } - } - } - } - return ret; - } - /** - * 客户端接口 - * */ - public Map clientuploadFTP(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - 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()); - boolean flag = ftps.open(); - File file = null; - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - String userkey =username + File.separator+ uuid+times + "." + entry.getKey(); - ftps.mkDir(File.separator+username); - if (flag) { - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - ftps.upload(file, File.separator+userkey, ""); - - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - ftps.close(); - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - ftps.close(); + ret = 1; + key = k; +// KeyObjectMap objectMap = new KeyObjectMap(ftp,k); + } catch (IOException e) { + System.out.println("FTP Object Is null"); + return -1; + } } } } - return ImgUrl; + return ret; } public static void fuzhi(String p1,String p2){ - String a=p1;//定义要进行复制的文件路径 + String a=p1; try{ File afile=new File(a); File bfile=new File(p2);//定义一个复制后的文件路径 @@ -186,14 +106,32 @@ public class FTPImageupload { byte[] date=new byte[512];//定义一个byte数组 int i=0; while((i=c.read(date))>0){//判断有没有读取到文件末尾 - d.write(date);//写数据 + d.write(date); } - c.close();//关闭流 - d.close();//关闭流 + 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; + } + + } diff --git a/src/main/java/cn/hellohao/service/impl/GroupServiceImpl.java b/src/main/java/cn/hellohao/service/impl/GroupServiceImpl.java index e1b9b98..93aa531 100644 --- a/src/main/java/cn/hellohao/service/impl/GroupServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/GroupServiceImpl.java @@ -39,6 +39,11 @@ public class GroupServiceImpl implements GroupService { return groupMapper.addgroup(group); } + @Override + public Integer GetCountFroUserType(Integer usertype) { + return groupMapper.GetCountFroUserType(usertype); + } + @Override @Transactional//默认遇到throw new RuntimeException(“…”);会回滚 public Integer delegroup(Integer id) { @@ -63,4 +68,10 @@ public class GroupServiceImpl implements GroupService { public Integer setgroup(Group group) { return groupMapper.setgroup(group); } + + @Override + public Group getGroupFroUserType(Integer usertype) { + return groupMapper.getGroupFroUserType(usertype); + } + } diff --git a/src/main/java/cn/hellohao/service/impl/ImgServiceImpl.java b/src/main/java/cn/hellohao/service/impl/ImgServiceImpl.java index d3e0381..1350dd4 100644 --- a/src/main/java/cn/hellohao/service/impl/ImgServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/ImgServiceImpl.java @@ -4,6 +4,7 @@ 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; @@ -200,7 +201,7 @@ public class ImgServiceImpl implements ImgService { } @Override - public Integer getusermemory(Integer userid) { + public Long getusermemory(Integer userid) { return imgMapper.getusermemory(userid); } @@ -213,4 +214,29 @@ public class ImgServiceImpl implements ImgService { public Images selectImgUrlByMD5(String md5key) { return imgMapper.selectImgUrlByMD5(md5key); } + + @Override + public List RecentlyUploaded(Integer userid) { + return imgMapper.RecentlyUploaded(userid); + } + + @Override + public List RecentlyUser() { + return imgMapper.RecentlyUser(); + } + + @Override + public Integer addGreat(Integer id) { + return imgMapper.addGreat(id); + } + + public List getyyyy(Integer userid){ + return imgMapper.getyyyy(userid); + } + + @Override + public List countByM(Images images) { + return imgMapper.countByM(images); + } + } diff --git a/src/main/java/cn/hellohao/service/impl/ImgTempServiceImpl.java b/src/main/java/cn/hellohao/service/impl/ImgTempServiceImpl.java new file mode 100644 index 0000000..fec1728 --- /dev/null +++ b/src/main/java/cn/hellohao/service/impl/ImgTempServiceImpl.java @@ -0,0 +1,36 @@ +package cn.hellohao.service.impl; + +import cn.hellohao.dao.ImgTempMapper; +import cn.hellohao.pojo.Images; +import cn.hellohao.pojo.ImgTemp; +import cn.hellohao.service.ImgTempService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** +* +*/ +@Service +public class ImgTempServiceImpl implements ImgTempService { + + @Autowired + ImgTempMapper imgDataExpMapper; + + + @Override + public List selectDelImgUidList(String datatime) { + return imgDataExpMapper.selectDelImgUidList(datatime); + } + + @Override + public Integer delImgAndExp(String imguid) { + return imgDataExpMapper.delImgAndExp(imguid); + } + + @Override + public Integer insertImgExp(ImgTemp imgDataExp) { + return imgDataExpMapper.insertImgExp(imgDataExp); + } +} diff --git a/src/main/java/cn/hellohao/service/impl/ImgreviewServiceImpl.java b/src/main/java/cn/hellohao/service/impl/ImgreviewServiceImpl.java index 159bf2f..9833dc4 100644 --- a/src/main/java/cn/hellohao/service/impl/ImgreviewServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/ImgreviewServiceImpl.java @@ -41,4 +41,10 @@ public class ImgreviewServiceImpl implements ImgreviewService { public int updateByPrimaryKey(Imgreview record) { return 0; } + + @Override + public Imgreview selectByusing(Integer using) { + return imgreviewMapper.selectByusing(using); + } + } diff --git a/src/main/java/cn/hellohao/service/impl/InitializationStorage.java b/src/main/java/cn/hellohao/service/impl/InitializationStorage.java index 00d8c63..6076489 100644 --- a/src/main/java/cn/hellohao/service/impl/InitializationStorage.java +++ b/src/main/java/cn/hellohao/service/impl/InitializationStorage.java @@ -1,9 +1,11 @@ package cn.hellohao.service.impl; +import cn.hellohao.auth.filter.SubjectFilter; import cn.hellohao.dao.KeysMapper; import cn.hellohao.pojo.Keys; import cn.hellohao.utils.Print; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @@ -20,16 +22,18 @@ import java.util.List; @Component @Order(2) public class InitializationStorage implements CommandLineRunner { + + @Value("${CROS_ALLOWED_ORIGINS}") + private String allowedOrigins; + @Autowired private KeysMapper keysMapper; @Override public void run(String... args) throws Exception { + SubjectFilter.WEBHOST = allowedOrigins; String name = ManagementFactory.getRuntimeMXBean().getName(); - //System.out.println(name); -// get pid String pid = name.split("@")[0]; - //System.out.println("Pid is:" + pid); intiStorage(); sout(); } @@ -55,14 +59,13 @@ public class InitializationStorage implements CommandLineRunner { } } } - //Print.Normal("66666666"); } public void sout(){ Print.Normal("______________________________________________"); - Print.Normal(" Hellohao-Open source "); + Print.Normal(" Hellohao Tbed "); Print.Normal(" Successful startup of the program "); - Print.Normal(" is OK! Open http://your ip:port "); + Print.Normal(" is OK! Open http:// yourIP:port "); Print.Normal("______________________________________________"); } } diff --git a/src/main/java/cn/hellohao/service/impl/KODOImageupload.java b/src/main/java/cn/hellohao/service/impl/KODOImageupload.java index 3d95768..ac71d37 100644 --- a/src/main/java/cn/hellohao/service/impl/KODOImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/KODOImageupload.java @@ -28,93 +28,57 @@ import java.util.UUID; @Service public class KODOImageupload { static String upToken; - static UploadManager uploadManager; + static BucketManager bucketManager; static Keys key; - public Map ImageuploadKODO(Map fileMap, String username, - Map fileMap2,Integer setday){ - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - try { - Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken); - DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename() - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "4"); - } - } catch (QiniuException ex) { - Response r = ex.response; - System.err.println(r.toString()); - try { - System.err.println(r.bodyString()); - } catch (QiniuException ex2) { - } - } - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); - } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey()); - try { - Response response = uploadManager.put(new File(imgurl),username + "/" + uuid+times + "." + entry.getKey(),upToken); - DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "4"); - } - new File(imgurl).delete(); - } catch (QiniuException ex) { - Response r = ex.response; - System.err.println(r.toString()); - try { - System.err.println(r.bodyString()); - } catch (QiniuException ex2) { - } - } - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); - } - return ImgUrl; + public ReturnImage ImageuploadKODO(Map fileMap, String username, Integer keyID){ + ReturnImage returnImage = new ReturnImage(); + Keys key = null; + 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()); } - } + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(key.getAccessKey(), key.getAccessSecret()); + String upToken = auth.uploadToken(key.getBucketname(),null,7200,null); + File file = null; + try { + for (Map.Entry entry : fileMap.entrySet()) { + String ShortUID = SetText.getShortUuid(); + java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); + file = entry.getValue(); + try { + Response response = uploadManager.put(file,username + "/" + ShortUID + "." + entry.getKey(),upToken); + DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); + returnImage.setUid(ShortUID); + returnImage.setImgname(username + "/" + ShortUID + "." + entry.getKey()); + returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + ShortUID + "." + entry.getKey()); + returnImage.setImgSize(entry.getValue().length()); + returnImage.setCode("200"); + } catch (QiniuException ex) { + Response r = ex.response; + System.err.println(r.toString()); + try { + System.err.println(r.bodyString()); + } catch (QiniuException ex2) { + } + } + } + }catch (Exception e){ + e.printStackTrace(); + returnImage.setCode("500"); + } + return returnImage; - // 转换文件方法 -// private File changeFile(MultipartFile multipartFile) throws Exception { -// // 获取文件名 -// String fileName = multipartFile.getOriginalFilename(); -// // 获取文件后缀 -// String prefix = fileName.substring(fileName.lastIndexOf(".")); -// // todo 修改临时文件文件名 -// File file = File.createTempFile(fileName, prefix); -// multipartFile.transferTo(file); -// return file; -// } + } //初始化 public static Integer Initialize(Keys k) { @@ -135,21 +99,22 @@ public class KODOImageupload { } else { cfg = new Configuration(Zone.zoneAs0()); } - uploadManager = new UploadManager(cfg); + UploadManager uploadManager = new UploadManager(cfg); Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret()); - upToken = auth.uploadToken(k.getBucketname()); + String upToken = auth.uploadToken(k.getBucketname(),null,7200,null);//auth.uploadToken(k.getBucketname()); + BucketManager bucketManager = new BucketManager(auth, cfg); BucketManager.FileListIterator fileListIterator = null; try { fileListIterator = bucketManager.createFileListIterator(k.getBucketname(), "", 1, "/"); FileInfo[] items = fileListIterator.next(); - System.out.println(items!=null); if(items!=null){ - key = k; ret = 1; + bucketManager = bucketManager; + key = k; } }catch (Exception e){ - System.out.println("KODO - Waiting for configuration"); + System.out.println("KODO Object Is null"); ret = -1; } } @@ -157,41 +122,14 @@ public class KODOImageupload { return ret; } - /** - * 客户端接口 - * */ - public Map clientuploadKODO(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - File file = null; - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey()); - try { - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken); - DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - } - } catch (QiniuException ex) { - Response r = ex.response; - System.err.println(r.toString()); - try { - System.err.println(r.bodyString()); - } catch (QiniuException ex2) { - } - } + public Boolean delKODO(Integer keyID, String fileName) { + boolean b = true; + try { + bucketManager.delete(key.getBucketname(), fileName); + } catch (Exception ex) { + b = false; } - return ImgUrl; + return b; } diff --git a/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java b/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java index 1cfa45f..6be7b97 100644 --- a/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java @@ -16,9 +16,9 @@ public class KeysServiceImpl implements KeysService { private KeysMapper keysMapper; @Override - public Keys selectKeys(Integer storageType) { + public Keys selectKeys(Integer id) { // TODO Auto-generated method stub - return keysMapper.selectKeys(storageType); + return keysMapper.selectKeys(id); } @Override diff --git a/src/main/java/cn/hellohao/service/impl/NOSImageupload.java b/src/main/java/cn/hellohao/service/impl/NOSImageupload.java index d84c24a..2eaf07a 100644 --- a/src/main/java/cn/hellohao/service/impl/NOSImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/NOSImageupload.java @@ -24,103 +24,31 @@ import cn.hellohao.pojo.Keys; @Service public class NOSImageupload { - static String BarrelName; static NosClient nosClient; static Keys key; - public Map Imageupload(Map fileMap, String username, - Map fileMap2,Integer setday){ - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename() - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0){ - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid+times + "." + entry.getKey()+"-"+deleimg+"-"+"1"); - } - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); + public ReturnImage Imageupload(Map fileMap, String username,Integer keyID){ + ReturnImage returnImage = new ReturnImage(); + File file = null; + try { + for (Map.Entry entry : fileMap.entrySet()) { + String ShortUID = SetText.getShortUuid(); + file = entry.getValue(); + nosClient.putObject(key.getBucketname(), username + "/" + ShortUID+ "." + entry.getKey(), file); + returnImage.setUid(ShortUID); + returnImage.setImgname(username + "/" + ShortUID+ "." + entry.getKey()); + returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + ShortUID + "." + entry.getKey()); + returnImage.setImgSize(entry.getValue().length()); + returnImage.setCode("200"); } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - String head = ""; - if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){ - head = "image/jpeg"; - }else if(entry.getKey().equals("png")){ - head = "image/png"; - }else if(entry.getKey().equals("bmp")){ - head = "image/bmp"; - }else if(entry.getKey().equals("gif")){ - head = "image/gif"; - }else{ - //System.err.println("未知格式文件,无法定义header头。"); - head = "image/"+entry.getKey(); - } - meta.setHeader("Content-Type", head);//image/jpeg - File file = new File(imgurl); - FileInputStream fileInputStream = new FileInputStream(file); - try { - nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), fileInputStream,meta); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "-" + deleimg + "-" + "1"); - } - boolean bb= new File(imgurl).getAbsoluteFile().delete(); - Print.Normal("删除情况"+bb); - } catch (Exception e) { - System.err.println("上传报错:" + e.getMessage()); - } - if(fileInputStream!=null){ - fileInputStream.close(); - Print.Normal("流已经关闭"); - } - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); - } - return ImgUrl; + }catch (Exception e){ + e.printStackTrace(); + returnImage.setCode("500"); } + return returnImage; } - // 转换文件方法 -// private File changeFile(MultipartFile multipartFile) throws Exception { -// // 获取文件名 -// String fileName = multipartFile.getOriginalFilename(); -// // 获取文件后缀 -// String prefix = fileName.substring(fileName.lastIndexOf(".")); -// // todo 修改临时文件文件名 -// File file = File.createTempFile(fileName, prefix); -// // MultipartFile to File -// multipartFile.transferTo(file); -// return file; -// } - //初始化网易NOS对象存储 public static Integer Initialize(Keys k) { @@ -131,54 +59,39 @@ public class NOSImageupload { && !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ){ // 初始化 Credentials credentials = new BasicCredentials(k.getAccessKey(), k.getAccessSecret()); - nosClient = new NosClient(credentials); + NosClient nosClient = new NosClient(credentials); nosClient.setEndpoint(k.getEndpoint()); - BarrelName = k.getBucketname(); ObjectListing objectListing = null; try { objectListing = nosClient.listObjects(k.getBucketname()); - key = k; ret = 1; + nosClient = nosClient; + key = k; }catch (Exception e){ - System.out.println("NOS - Waiting for configuration"); + System.out.println("NOS Object Is null"); ret = -1; } } } - //throw new StorageSourceInitException("当前数据源配置不完整,请管理员前往后台配置。"); + //throw new StorageSourceInitException("当前数据源配置不完整,请管理员前往后台配置。"); return ret; } - /** - * 客户端接口 - * */ - public Map clientuploadNOS(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - File file = null; - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - try { - Print.warning(entry.getValue().getSize()); - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file); - //ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize())); - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - } - } catch (Exception e) { - System.out.println("上传报错:" + e.getMessage()); + + public Boolean delNOS(Integer keyID, String fileName) { + boolean b =true; + try { + //这种方法不能删除指定文件夹下的文件 + boolean isExist = nosClient.doesObjectExist(key.getBucketname(), fileName, null); + if (isExist) { + nosClient.deleteObject(key.getBucketname(), fileName); } + } catch (Exception e) { + e.printStackTrace(); + b =false; } - return ImgUrl; + return b; } + } diff --git a/src/main/java/cn/hellohao/service/impl/OSSImageupload.java b/src/main/java/cn/hellohao/service/impl/OSSImageupload.java index 37b7113..82082f2 100644 --- a/src/main/java/cn/hellohao/service/impl/OSSImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/OSSImageupload.java @@ -2,125 +2,66 @@ 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.aliyun.oss.OSS; import com.aliyun.oss.OSSClient; -import com.aliyun.oss.model.OSSObjectSummary; +import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.ObjectListing; 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 OSSImageupload { - static String BarrelName; static OSSClient ossClient; static Keys key; - public Map ImageuploadOSS(Map fileMap, String username, - Map fileMap2,Integer setday){ - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - String head = ""; - if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){ - head = "image/jpeg"; - }else if(entry.getKey().equals("png")){ - head = "image/png"; - }else if(entry.getKey().equals("bmp")){ - head = "image/bmp"; - }else if(entry.getKey().equals("gif")){ - head = "image/gif"; - }else{ - //System.err.println("位置格式文件,无法定义header头。"); - head = "image/"+entry.getKey(); - } - meta.setHeader("Content-Type", head);//image/jpeg - System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey()); - ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),file,meta); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename() - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "2"); - } - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); + public ReturnImage ImageuploadOSS(Map 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 entry : fileMap.entrySet()) { + String ShortUID = SetText.getShortUuid();//UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 + java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); +// String times = format1.format(new Date()); + file = entry.getValue(); + System.out.println("待上传的图片:"+username + "/" + ShortUID + "." + entry.getKey()); + ossClient.putObject(key.getBucketname(), username + "/" + ShortUID + "." + entry.getKey(),file); + returnImage.setUid(ShortUID); + returnImage.setImgname(username + "/" + ShortUID + "." + entry.getKey());//entry.getValue().getOriginalFilename() + returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + ShortUID + "." + entry.getKey()); + returnImage.setImgSize(file.length()); + returnImage.setCode("200"); } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - String head = ""; - if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){ - head = "image/jpeg"; - }else if(entry.getKey().equals("png")){ - head = "image/png"; - }else if(entry.getKey().equals("bmp")){ - head = "image/bmp"; - }else if(entry.getKey().equals("gif")){ - head = "image/gif"; - }else{ - //System.err.println("位置格式文件,无法定义header头。"); - head = "image/"+entry.getKey(); - } - meta.setHeader("Content-Type", head);//image/jpeg - System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey()); - ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),new File(imgurl),meta); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - new File(imgurl).delete(); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "2"); - } - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); - } - return ImgUrl; + }catch (Exception e){ + e.printStackTrace(); + returnImage.setCode("500"); } + return returnImage; + + } //初始化 public static Integer Initialize(Keys k) { + int ret = -1; ObjectListing objectListing = null; - if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null + if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getAccessKey()!=null && k.getEndpoint()!=null && k.getBucketname()!=null && k.getRequestAddress()!=null ) { - if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") + if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getAccessKey().equals("") && !k.getEndpoint().equals("") && !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) { - ossClient = new OSSClient(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret()); + OSS ossClient = new OSSClientBuilder().build(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret()); try { objectListing = ossClient.listObjects(k.getBucketname()); - key = k; ret=1; + ossClient = ossClient; + key = k; } catch (Exception e) { - System.out.println("OSS - Waiting for configuration"); + System.out.println("OSS Object Is null"); ret = -1; } } @@ -128,49 +69,16 @@ public class OSSImageupload { return ret; } - - - /** - * 客户端接口 - * */ - public Map clientuploadOSS(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - File file = null; - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - String head = ""; - if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){ - head = "image/jpeg"; - }else if(entry.getKey().equals("png")){ - head = "image/png"; - }else if(entry.getKey().equals("bmp")){ - head = "image/bmp"; - }else if(entry.getKey().equals("gif")){ - head = "image/gif"; - }else{ - //System.err.println("位置格式文件,无法定义header头。"); - head = "image/"+entry.getKey(); - } - meta.setHeader("Content-Type", head);//image/jpeg - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),file,meta); - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - } - } - return ImgUrl; - + public boolean delOSS(Integer keyID, String fileName){ + boolean b =true; + try { + ossClient.deleteObject(key.getBucketname(), fileName); + } catch (Exception e) { + e.printStackTrace(); + b = false; + } + return b; } + } diff --git a/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java b/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java new file mode 100644 index 0000000..9dc72ba --- /dev/null +++ b/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java @@ -0,0 +1,53 @@ +package cn.hellohao.service.impl; + +import cn.hellohao.service.IRedisService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Service; + +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@Service +public class RedisServiceImpl implements IRedisService { + @Autowired + private StringRedisTemplate stringRedisTemplate; + @Autowired + private RedisTemplate redisTemplate; + + + @Override + public void setValue(String key, Map value) { + ValueOperations vo = redisTemplate.opsForValue(); + vo.set(key, value); + redisTemplate.expire(key, 1, TimeUnit.HOURS); // 这里指的是1小时后失效 + } + + @Override + public Object getValue(String key) { + ValueOperations vo = redisTemplate.opsForValue(); + return vo.get(key); + } + + @Override + public void setValue(String key, String value) { + ValueOperations vo = redisTemplate.opsForValue(); + vo.set(key, value); + redisTemplate.expire(key, 3, TimeUnit.MINUTES); // 这里指的是1小时后失效 时HOURS 分 MINUTES + } + + @Override + public void setValue(String key, Object value) { + ValueOperations vo = redisTemplate.opsForValue(); + vo.set(key, value); + redisTemplate.expire(key, 1, TimeUnit.HOURS); // 这里指的是1小时后失效 + } + + @Override + public Object getMapValue(String key) { + ValueOperations vo = redisTemplate.opsForValue(); + return vo.get(key); + } +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/service/impl/UFileImageupload.java b/src/main/java/cn/hellohao/service/impl/UFileImageupload.java index 8b4de69..e6bebab 100644 --- a/src/main/java/cn/hellohao/service/impl/UFileImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/UFileImageupload.java @@ -17,103 +17,52 @@ public class UFileImageupload { static UpYun uFile; static Keys key; - public Map ImageuploadUSS(Map fileMap, String username, - Map fileMap2,Integer setday) { - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - uFile.setContentMD5(UpYun.md5(file)); - boolean result = uFile.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true); - if(result){ - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename() - returnImage.setImgurl(key.getRequestAddress() + "/" +username + "/" + uuid+times + "." + entry.getKey());//key.getRequestAddress() + "/" + - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3"); - } - }else{ - System.err.println("上传失败"); - } + public ReturnImage ImageuploadUFile(Map 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 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.setUid(ShortUID); + 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){ - ImgUrl.put(null, 500); } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - uFile.setContentMD5(UpYun.md5(new File(imgurl))); - boolean result = uFile.writeFile(username + "/" + uuid+times + "." + entry.getKey(), new File(imgurl), true); - if(result){ - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3"); - } - }else{ - Print.warning("上传失败"); - } - new File(imgurl).delete(); - } - }catch(Exception e){ - ImgUrl.put(null, 500); - } - return ImgUrl; + }catch(Exception e){ + returnImage.setCode("500"); } + return returnImage; + } -// // 转换文件方法 -// private File changeFile(MultipartFile multipartFile) throws Exception { -// // 获取文件名 -// String fileName = multipartFile.getName();//getOriginalFilename -// // 获取文件后缀 -// String prefix = fileName.substring(fileName.lastIndexOf(".")); -// // todo 修改临时文件文件名 -// File file = File.createTempFile(fileName, prefix); -// // MultipartFile to File -// multipartFile.transferTo(file); -// return file; -// } - //ufile初始化 public static Integer Initialize(Keys k) { int ret = -1; - if(k.getEndpoint()!=null && k.getAccessSecret()!=null + if(k.getAccessSecret()!=null && k.getAccessKey()!=null && k.getBucketname()!=null && k.getRequestAddress()!=null ) { - if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") + if(!k.getAccessSecret().equals("") && !k.getAccessKey().equals("") && !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) { - // 初始化 // 创建UpYun实例。 - uFile = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret()); + UpYun uFile = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret()); List items = null; try { - items = uFile.readDir("/",null); - key = k; + items = uFile.readDir("/",null); ret = 1; + uFile = uFile; + key = k; } catch (Exception e) { - System.out.println("UFile - Waiting for configuration"); + System.out.println("UFile Object Is null"); ret = -1; } } @@ -121,45 +70,15 @@ public class UFileImageupload { return ret; } - - /** - * 客户端接口 - * */ - public Map clientuploadUSS(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - File file = null; - Map ImgUrl = new HashMap<>(); - //设置Header - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - // 上传文件流。 - System.out.println("客户端:待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey()); - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - // 例2:采用数据流模式上传文件(节省内存),自动创建父级目录 - uFile.setContentMD5(UpYun.md5(file)); - boolean result = uFile.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true); - if(result){ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - - //ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize())); - }else{ - System.err.println("上传失败"); - } - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - } + 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 ImgUrl; + return b; } - } diff --git a/src/main/java/cn/hellohao/service/impl/USSImageupload.java b/src/main/java/cn/hellohao/service/impl/USSImageupload.java index 9b06c21..bc2845a 100644 --- a/src/main/java/cn/hellohao/service/impl/USSImageupload.java +++ b/src/main/java/cn/hellohao/service/impl/USSImageupload.java @@ -20,89 +20,53 @@ public class USSImageupload { static UpYun upyun; static Keys key; - public Map ImageuploadUSS(Map fileMap, String username, - Map fileMap2,Integer setday) { - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - try { - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile(entry.getValue()); - upyun.setContentMD5(UpYun.md5(file)); - boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true); - if(result){ - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename() - returnImage.setImgurl(key.getRequestAddress() + "/" +username + "/" + uuid+times + "." + entry.getKey());//key.getRequestAddress() + "/" + - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3"); - } - }else{ - System.err.println("上传失败"); - } + public ReturnImage ImageuploadUSS(Map 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 entry : fileMap.entrySet()) { + String ShortUID = SetText.getShortUuid(); + file = entry.getValue(); + upyun.setContentMD5(UpYun.md5(file)); + boolean result = upyun.writeFile(username + "/" + ShortUID + "." + entry.getKey(), file, true); + if(result){ + returnImage.setUid(ShortUID); + 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){ - e.printStackTrace(); - ImgUrl.put(null, 500); } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - try { - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String imgurl = entry.getValue(); - upyun.setContentMD5(UpYun.md5(new File(imgurl))); - boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), new File(imgurl), true); - if(result){ - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3"); - } - }else{ - Print.warning("上传失败"); - } - new File(imgurl).delete(); - } - }catch (Exception e){ - e.printStackTrace(); - ImgUrl.put(null, 500); - } - return ImgUrl; + }catch (Exception e){ + e.printStackTrace(); + returnImage.setCode("500"); } + return returnImage; + } //初始化 public static Integer Initialize(Keys k) { int ret = -1; - if(k.getEndpoint()!=null && k.getAccessSecret()!=null - && k.getBucketname()!=null && k.getRequestAddress()!=null ) { - if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") - && !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) { + if(k.getStorageType()!=null && k.getAccessKey() != null && k.getAccessSecret() != null && k.getBucketname() != null + && k.getRequestAddress() !=null ) { + if(!k.getStorageType().equals("") && !k.getAccessKey().equals("") && !k.getAccessSecret().equals("") && !k.getBucketname().equals("") + && !k.getRequestAddress().equals("") ) { // 初始化 // 创建UpYun实例。 - upyun = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret()); + UpYun upyun = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret()); List items = null; try { - items = upyun.readDir("/",null); - key = k; + items = upyun.readDir("/",null); ret = 1; + upyun = upyun; + key = k; } catch (Exception e) { - System.out.println("USS - Waiting for configuration"); + System.out.println("USS Object Is null"); ret = -1; } } @@ -110,44 +74,15 @@ public class USSImageupload { return ret; } - - /** - * 客户端接口 - * */ - public Map clientuploadUSS(Map fileMap, String username, UploadConfig uploadConfig) throws Exception { - File file = null; - Map ImgUrl = new HashMap<>(); - //设置Header - ObjectMetadata meta = new ObjectMetadata(); - meta.setHeader("Content-Disposition", "inline"); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - file = SetFiles.changeFile_c(entry.getValue()); - // 上传文件流。 - System.out.println("客户端:待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey()); - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - // 例2:采用数据流模式上传文件(节省内存),自动创建父级目录 - upyun.setContentMD5(UpYun.md5(file)); - boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true); - if(result){ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - - //ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize())); - }else{ - System.err.println("上传失败"); - } - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage, -1); - } + public Boolean delUSS(Integer keyID, String fileName) { + boolean b = true; + try { + boolean result = upyun.deleteFile(fileName, null); + } catch (Exception e) { + e.printStackTrace(); + b=false; } - return ImgUrl; + return b; } diff --git a/src/main/java/cn/hellohao/service/impl/UploadServicel.java b/src/main/java/cn/hellohao/service/impl/UploadServicel.java index f8f96bb..433773b 100644 --- a/src/main/java/cn/hellohao/service/impl/UploadServicel.java +++ b/src/main/java/cn/hellohao/service/impl/UploadServicel.java @@ -1,20 +1,25 @@ package cn.hellohao.service.impl; -import cn.hellohao.controller.UpdateImgController; import cn.hellohao.dao.*; import cn.hellohao.pojo.*; +import cn.hellohao.service.ImgTempService; +import cn.hellohao.service.SysConfigService; 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.baidu.aip.contentcensor.AipContentCensor; +import com.baidu.aip.contentcensor.EImgType; import org.apache.commons.codec.digest.DigestUtils; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockMultipartFile; import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; @@ -30,6 +35,8 @@ public class UploadServicel { @Autowired ConfigMapper configMapper; @Autowired + SysConfigService sysConfigService; + @Autowired UploadConfigMapper uploadConfigMapper; @Autowired KeysMapper keysMapper; @@ -37,177 +44,329 @@ public class UploadServicel { ImgMapper imgMapper; @Autowired UserMapper userMapper; + @Autowired + ImgreviewMapper imgreviewMapper; + @Autowired + ImgTempService imgTempService; - public Msg uploadForLoc(HttpSession session, HttpServletRequest request, - MultipartFile multipartFile, Integer setday, String upurlk, String[] iparr) { + + public Msg uploadForLoc(HttpServletRequest request, + MultipartFile multipartFile, Integer setday, String imgUrl, JSONArray selectTreeList) { Msg msg = new Msg(); - JSONArray jsonArray = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - Config config = configMapper.getSourceype(); - UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig(); - String userip = GetIPS.getIpAddr(request); - java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd"); - User u = (User) session.getAttribute("user"); - Integer usermemory = 0; - Integer memory = 0; - Integer sourcekey = 0; - Integer maxsize = 0; - String userpath = "tourist"; - String md5key = ""; - //FileInputStream fis = null; - File file = SetFiles.changeFile_new(multipartFile); - try { - md5key = DigestUtils.md5Hex(new FileInputStream(file)); - if(!TypeDict.checkImgType(file)) { - msg.setCode("4000"); + try{ + JSONObject jsonObject = new JSONObject(); + UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig(); + String userip = GetIPS.getIpAddr(request); + Subject subject = SecurityUtils.getSubject(); + User u = (User) subject.getPrincipal(); + if(null!=u){ + u = userMapper.getUsers(u); + } + Integer sourceKeyId = 0; + String md5key = null; + FileInputStream fis = null; + File file =null; + if(imgUrl==null){ + file = SetFiles.changeFile_new(multipartFile); + }else{ + //说明是URL上传 + Msg imgData = uploadForURL(request, imgUrl); + if(imgData.getCode().equals("200")){ + file = new File((String) imgData.getData()); + }else{ + return imgData; + } + } + String imguid = UUID.randomUUID().toString().replace("-", ""); + //判断上传前的一些用户限制信息 + Msg msg1 = updateImgCheck(u,uploadConfig); + if(!msg1.getCode().equals("300")){ + return msg1; + } + + //判断可用容量 + sourceKeyId = group.getKeyid(); + Keys key = keysMapper.selectKeys(sourceKeyId); + Long tmp = (memory == -1 ? -2 : UsedTotleMemory); + if (tmp >= memory) { + msg.setCode("4005"); + msg.setInfo(u==null?"游客空间已用尽":"您的可用空间不足"); return msg; } - } catch (Exception e) { - e.printStackTrace(); - msg.setCode("5000"); - return msg; - } - //判断图片是否存在 - if(imgMapper.md5Count(md5key)>0){ - Print.warning("图片存在啦"); - Images images = imgMapper.selectImgUrlByMD5(md5key); - jsonObject.put("imgurls", images.getImgurl()); - jsonObject.put("imgnames",file.getName()); - jsonArray.add(jsonObject); - msg.setData(jsonArray); - return msg; - } - String prefix = file.getName().substring(file.getName().lastIndexOf(".")+1); - MultipartFile mf =null; - try{ - InputStream inputStream = new FileInputStream(file); - mf = new MockMultipartFile(file.getName(), inputStream); - inputStream.close(); - }catch (Exception e){ - System.out.println("0000000"); - } - if (uploadConfig.getBlacklist() != null) { - iparr = uploadConfig.getBlacklist().split(";"); - for (String s : iparr) { - if (s.equals(userip)) { - msg.setCode("911"); - return msg; - } + //判断图片有没有超出设定大小 + if (file.length() > TotleMemory) { + System.err.println("文件大小:"+file.length()); + System.err.println("最大限制:"+TotleMemory); + msg.setCode("4006"); + msg.setInfo("图像超出系统限制大小"); + return msg; } - } -// if (Integer.parseInt(Base64Encryption.decryptBASE64(upurlk)) != yzupdate()) { - if (!upurlk.equals(UpdateImgController.vu)) { - msg.setCode("4003"); - return msg; - } - //验证文件是否是图片 - if (u == null) { - sourcekey = GetCurrentSource.GetSource(null); - memory = uploadConfig.getVisitormemory(); - maxsize = uploadConfig.getFilesizetourists(); - usermemory = imgMapper.getusermemory(0); - if (usermemory == null) { - usermemory = 0; + try { + fis = new FileInputStream(file); + md5key = DigestUtils.md5Hex(fis); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("未获取到图片的MD5,成成UUID"); } - } else { - userpath = u.getUsername(); - sourcekey = GetCurrentSource.GetSource(u.getId()); - memory = userMapper.getUsers(u.getEmail()).getMemory(); - maxsize = uploadConfig.getFilesizeuser(); - usermemory = imgMapper.getusermemory(u.getId()); - if (usermemory == null) { - usermemory = 0; + Msg fileMiME = TypeDict.FileMiME(file, uploadConfig.getSuffix()); + if(!fileMiME.getCode().equals("200")) { + //非图像文本 + msg.setCode("4000"); + msg.setInfo(fileMiME.getInfo()); + return msg; } - } - if (uploadConfig.getUrltype() == 2) { - userpath = dateFormat.format(new Date()); - } - Keys key = keysMapper.selectKeys(sourcekey); - int tmp = (memory == -1 ? -2 : (usermemory / 1024)); - if (tmp >= memory) { - msg.setCode("4005"); - return msg; - } - long stime = System.currentTimeMillis(); - Map map = new HashMap<>(); - if (mf.getSize() > maxsize * 1024 * 1024) { - msg.setCode("4006"); - return msg; - } - String fileName = mf.getOriginalFilename(); - if (!mf.isEmpty()) { - map.put(prefix, mf);//prefix - } - Map m = null; - m = GetSource.storageSource(key.getStorageType(), map, userpath, null, setday); - Images img = new Images(); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); - for (Map.Entry entry : m.entrySet()) { - if(entry.getKey()!=null){ - if (key.getStorageType() == 5) { - if (config.getDomain() != null) { - jsonObject.put("imgurls", config.getDomain() +"/"+ entry.getKey().getImgurl()); - jsonObject.put("imgnames", entry.getKey().getImgname()); - img.setImgurl(config.getDomain() +"/"+ entry.getKey().getImgurl()); - } else { - jsonObject.put("imgurls", config.getDomain() +"/"+ entry.getKey().getImgurl()); - jsonObject.put("imgnames", entry.getKey().getImgname()); - img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() +"/"+ entry.getKey().getImgurl());//图片链接 + if(md5key==null || md5key.equals("")){ + md5key = UUID.randomUUID().toString().replace("-", ""); + } + String prefix = file.getName().substring(file.getName().lastIndexOf(".")+1); + //判断黑名单 + if (uploadConfig.getBlacklist() != null) { + String[] iparr = uploadConfig.getBlacklist().split(";"); + for (String s : iparr) { + if (s.equals(userip)) { + file.delete(); + msg.setCode("4003"); + msg.setInfo("你暂时不能上传"); + return msg; } - } else { - jsonObject.put("imgurls", entry.getKey().getImgurl()); - jsonObject.put("imgnames", entry.getKey().getImgname()); - img.setImgurl( entry.getKey().getImgurl()); } - jsonArray.add(jsonObject); + } + + Map map = new HashMap<>(); + if (file.exists()) { + map.put(prefix, file);//prefix + } + long stime = System.currentTimeMillis(); + Map m = null; + 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")){ + String imgurl = returnImage.getImgurl(); + Long imgsize = returnImage.getImgSize(); + String imgname = returnImage.getImgname(); + img.setImgurl(imgurl); img.setUpdatetime(df.format(new Date())); - img.setSource(key.getStorageType()); + img.setSource(key.getId()); img.setUserid(u == null ? 0 : u.getId()); - img.setSizes((entry.getValue()) / 1024); + img.setSizes(imgsize.toString()); if(uploadConfig.getUrltype()==2){ - //img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), "", "")); - String[] imgname = entry.getKey().getImgurl().split ("/"); - String name = ""; - for (int i = 0; i < imgname.length; i++) { - if(i>2 && i!=imgname.length-1){ - name+=imgname[i]+"/"; - } - if(i==imgname.length-1){ - name+=imgname[i]; - } - } - img.setImgname(entry.getKey().getImgname()); + img.setImgname(imgname); }else{ - img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", "")); + 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.setImgtype(setday > 0 ? 1 : 0); img.setAbnormal(userip); img.setMd5key(md5key); + img.setImguid(imguid); + img.setFormat(fileMiME.getData().toString()); + img.setShortlink(returnImage.getUid()); userMapper.insertimg(img); 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("name", imgname); + jsonObject.put("imguid",img.getImguid()); + jsonObject.put("shortLink", img.getShortlink()); + //启动鉴黄线程 + new Thread(()->{LegalImageCheck(img);}).start(); + }else{ msg.setCode("5001"); + msg.setInfo("上传服务内部错误"); return msg; } + file.delete(); + msg.setData(jsonObject); + return msg; + }catch (Exception e){ + e.printStackTrace(); + msg.setInfo("上传时发生了一些错误"); + msg.setCode("110500"); + return msg; + } + + } + + + //通过图片Url上传图片 + public static Msg uploadForURL(HttpServletRequest request, String imgurl){ + final Msg msg = new Msg(); + //先判断是不是有效链接 +// final boolean valid = ImgUrlUtil.isValid(imgurl); + if(true){ + Long imgsize = null; + try { + imgsize = ImgUrlUtil.getFileLength(imgurl); + if(imgsize>0){ +// String uuid= UUID.randomUUID().toString().replace("-", ""); + String ShortUID = SetText.getShortUuid(); + String savePath = request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator; + Map bl =ImgUrlUtil.downLoadFromUrl (imgurl, ShortUID, savePath); + if((Boolean) bl.get("res")==true){ +// File file = new File(); + msg.setCode("200"); + msg.setData(bl.get("imgPath"));//savePath + File.separator + ShortUID + return msg; + }else{ + if(bl.get("StatusCode").equals("110403")){ + msg.setInfo("该链接非图像文件,无法上传"); + }else{ + msg.setInfo("该链接暂时无法上传"); + } + msg.setCode("500"); + } + }else{ + msg.setCode("500"); + msg.setInfo("获取资源失败"); + } + } catch (IOException e) { + msg.setCode("500"); + msg.setInfo("获取资源失败"); + } + }else{ + msg.setCode("500"); + msg.setInfo("该链接无效"); } - msg.setData(jsonArray); return msg; } - public String uploadForURL() { - return ""; + + public static Group group; //上传用户或游客的所属分组 + public static Long memory;//上传用户或者游客的分配容量 memory + 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; + try { + dateFormat = new SimpleDateFormat("yyyy/MM/dd"); + if (user == null) { + //用户没有登陆,值判断游客能不能上传即可 + if(uploadConfig.getIsupdate()!=1){ + msg.setCode("1000"); + msg.setInfo("系统已禁用游客上传"); + return msg; + } + group = GetCurrentSource.GetSource(null); + memory = Long.valueOf(uploadConfig.getVisitormemory());//单位 B 游客设置总量 + TotleMemory = Long.valueOf(uploadConfig.getFilesizetourists());//单位 B 游客单文件大小 + UsedTotleMemory = imgMapper.getusermemory(0)==null?0L : imgMapper.getusermemory(0);//单位 B + } else { + updatePath = user.getUsername(); + group= GetCurrentSource.GetSource(user.getId()); + memory = Long.valueOf(user.getMemory())*1024*1024;//单位 B + TotleMemory = Long.valueOf(uploadConfig.getFilesizeuser());//单位 B + UsedTotleMemory = imgMapper.getusermemory(user.getId())==null?0L:imgMapper.getusermemory(user.getId());//单位 B + } + //判断上传的图片目录结构类型 + if (uploadConfig.getUrltype() == 2) { + updatePath = dateFormat.format(new Date()); + } + msg.setCode("300"); + } catch (Exception e) { + e.printStackTrace(); + msg.setCode("500"); + } + return msg; } - private Integer yzupdate() { - Calendar cal = Calendar.getInstance(); - int y = cal.get(Calendar.YEAR); - int m = cal.get(Calendar.MONTH); - int d = cal.get(Calendar.DATE); - //int h=cal.get(Calendar.HOUR_OF_DAY); - //int mm=cal.get(Calendar.MINUTE); - return y + m + d + 999; + private synchronized void LegalImageCheck(Images images){ + System.out.println("非法图像鉴别进程启动"); + Imgreview imgreview = null; + try { + imgreview = imgreviewMapper.selectByusing(1); + } catch (Exception e) { + Print.warning("获取鉴别程序的时候发生错误"); + e.printStackTrace(); + } + //判断哪个鉴别平台 + if(null != imgreview){ + LegalImageCheckForBaiDu(imgreview,images); + } + } + + private void LegalImageCheckForBaiDu(Imgreview imgreview,Images images){ + System.out.println("非法图像鉴别进程启动-BaiDu"); +// Imgreview imgreview = imgreviewService.selectByPrimaryKey(1); + 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) { + //1:合规,2:不合规,3:疑似,4:审核失败 + for (Object datum : data) { + com.alibaba.fastjson.JSONObject imgdata = (com.alibaba.fastjson.JSONObject) datum; + if (imgdata.getInteger("type") == 1) { + //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(); + 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(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String currdate = format.format(d); + System.out.println("现在的日期是:" + currdate); + Calendar ca = Calendar.getInstance(); + ca.setTime(d); + ca.add(Calendar.DATE, setday);// num为增加的天数,可以改变的 + d = ca.getTime(); + String enddate = format.format(d); + System.out.println("到期的日期:" + enddate); + return enddate; + } + + } diff --git a/src/main/java/cn/hellohao/service/impl/UserServiceImpl.java b/src/main/java/cn/hellohao/service/impl/UserServiceImpl.java index c54a9bc..534f68e 100644 --- a/src/main/java/cn/hellohao/service/impl/UserServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/UserServiceImpl.java @@ -32,9 +32,9 @@ public class UserServiceImpl implements UserService { } @Override - public User getUsers(String email) { + public User getUsers(User user) { // TODO Auto-generated method stub - return userMapper.getUsers(email); + return userMapper.getUsers(user); } @Override diff --git a/src/main/java/cn/hellohao/utils/GetCurrentSource.java b/src/main/java/cn/hellohao/utils/GetCurrentSource.java index 1ff7663..8d80222 100644 --- a/src/main/java/cn/hellohao/utils/GetCurrentSource.java +++ b/src/main/java/cn/hellohao/utils/GetCurrentSource.java @@ -40,16 +40,53 @@ public class GetCurrentSource { } - public static Integer GetSource(Integer userid){ - Integer ret = 0; - if(userid==null){ - Group group = groupService.idgrouplist(1); - ret = group.getKeyid(); - }else{ - User user = userService.getUsersid(userid); - Group group = groupService.idgrouplist(user.getGroupid()); - ret = group.getKeyid(); + + public static Group GetSource(Integer userid) { + //UserType 0-未分配 1-游客 2-用户 3-管理员 + User user =null; + if(userid!=null){ + User u = new User(); + u.setId(userid); + user = userService.getUsers(u); } - return ret; + Group group =null; + if(user==null){ + //游客 + Integer count = groupService.GetCountFroUserType(1); + if(count>0){ + group = groupService.getGroupFroUserType(1); + }else{ + group = groupService.idgrouplist(1); + } + }else{ + //用户 + if(user.getGroupid()!=1){ + //说明自定义过的优先 + group = groupService.idgrouplist(user.getGroupid()); + }else{ + //默认的,用的是group主键为1的 但是还需要看看用户组有没有设置,比如管理员 用户 + if(user.getLevel()>1){ + //先查询管理员用户组有没有 如果有就用 没有就默认 + Integer count = groupService.GetCountFroUserType(3); + if(count>0){ + group = groupService.getGroupFroUserType(3); + }else{ + group = groupService.idgrouplist(1); + } + }else{ + //先查询普通用户组有没有 如果有就用 没有就默认 + Integer count = groupService.GetCountFroUserType(2); + if(count>0){ + group = groupService.getGroupFroUserType(2); + + }else{ + group = groupService.idgrouplist(1); + } + } + } + } + return group; } + + } diff --git a/src/main/java/cn/hellohao/utils/GetSource.java b/src/main/java/cn/hellohao/utils/GetSource.java index 6930fbf..4abf770 100644 --- a/src/main/java/cn/hellohao/utils/GetSource.java +++ b/src/main/java/cn/hellohao/utils/GetSource.java @@ -5,6 +5,7 @@ import cn.hellohao.pojo.ReturnImage; import cn.hellohao.service.impl.*; import org.springframework.web.multipart.MultipartFile; +import java.io.File; import java.util.Map; /** @@ -13,8 +14,7 @@ import java.util.Map; * @date 2019/11/7 17:12 */ public class GetSource { - public static Map storageSource(Integer type, Map fileMap, String userpath, - Map filename,Integer setday){ + public static ReturnImage storageSource(Integer type, Map fileMap, String userpath,Integer keyID){ NOSImageupload nosImageupload = SpringContextHolder.getBean(NOSImageupload.class); OSSImageupload ossImageupload = SpringContextHolder.getBean(OSSImageupload.class); USSImageupload ussImageupload = SpringContextHolder.getBean(USSImageupload.class); @@ -22,24 +22,24 @@ public class GetSource { COSImageupload cosImageupload = SpringContextHolder.getBean(COSImageupload.class); FTPImageupload ftpImageupload = SpringContextHolder.getBean(FTPImageupload.class); UFileImageupload uFileImageupload = SpringContextHolder.getBean(UFileImageupload.class); - Map m = null; + ReturnImage returnImage = null; try { if(type==1){ - m = nosImageupload.Imageupload(fileMap, userpath,filename,setday); + returnImage = nosImageupload.Imageupload(fileMap, userpath,keyID); }else if (type==2){ - m = ossImageupload.ImageuploadOSS(fileMap, userpath,filename,setday); + returnImage = ossImageupload.ImageuploadOSS(fileMap, userpath,keyID); }else if(type==3 ){ - m = ussImageupload.ImageuploadUSS(fileMap, userpath,filename,setday); + returnImage = ussImageupload.ImageuploadUSS(fileMap, userpath,keyID); }else if(type==4){ - m = kodoImageupload.ImageuploadKODO(fileMap, userpath,filename,setday); + returnImage = kodoImageupload.ImageuploadKODO(fileMap, userpath,keyID); }else if(type==5){ - m = LocUpdateImg.ImageuploadLOC(fileMap, userpath,filename,setday); + returnImage = LocUpdateImg.ImageuploadLOC(fileMap, userpath,keyID); }else if(type==6){ - m = cosImageupload.ImageuploadCOS(fileMap, userpath,filename,setday); + returnImage = cosImageupload.ImageuploadCOS(fileMap, userpath,keyID);; }else if(type==7){ - m = ftpImageupload.ImageuploadFTP(fileMap, userpath,filename,setday); + returnImage = ftpImageupload.ImageuploadFTP(fileMap, userpath,keyID); }else if(type==8){ - m = uFileImageupload.ImageuploadUSS(fileMap, userpath,filename,setday); + returnImage = uFileImageupload.ImageuploadUFile(fileMap, userpath,keyID); } else{ new StorageSourceInitException("GetSource类捕捉异常:未找到存储源"); @@ -48,7 +48,7 @@ public class GetSource { new StorageSourceInitException("GetSource类捕捉异常:",e); e.printStackTrace(); } - return m; + return returnImage; } diff --git a/src/main/java/cn/hellohao/utils/ImgUrlUtil.java b/src/main/java/cn/hellohao/utils/ImgUrlUtil.java index 51daace..43a3824 100644 --- a/src/main/java/cn/hellohao/utils/ImgUrlUtil.java +++ b/src/main/java/cn/hellohao/utils/ImgUrlUtil.java @@ -1,10 +1,14 @@ package cn.hellohao.utils; import cn.hellohao.TbedApplication; +import cn.hellohao.pojo.Msg; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; /* 操作网络url图片工具类 @@ -47,6 +51,38 @@ public class ImgUrlUtil { } } + /* + * 检测Url的响应值 + * 判断是否能访问。 + * */ + public static Map checkURLStatusCode(String urlStr){ + Map map = new HashMap<>(); + try { + URL url = new URL(urlStr); + URLConnection rulConnection = url.openConnection(); + HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection; + httpUrlConnection.setConnectTimeout(300000); + httpUrlConnection.setReadTimeout(300000); + httpUrlConnection.connect(); + String code = new Integer(httpUrlConnection.getResponseCode()).toString(); + String message = httpUrlConnection.getResponseMessage(); + System.out.println("getResponseCode code ="+ code); + System.out.println("getResponseMessage message ="+ message); + if(!code.startsWith("2") && !code.startsWith("3")){ + map.put("Check","false"); + map.put("StatusCode",code); + throw new Exception("ResponseCode is not begin with 2,code="+code); + } + map.put("Check","true"); + System.out.println("连接正常"); + }catch(Exception ex){ + System.out.println(ex.getMessage()); + } + + return map; + } + + /** * 从网络Url中下载文件 * @param urlStr @@ -54,32 +90,72 @@ public class ImgUrlUtil { * @param savePath * @throws IOException */ - public static boolean downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{ - URL url = new URL(urlStr); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - //设置超时间为3秒 - conn.setConnectTimeout(5*1000); - //防止屏蔽程序抓取而返回403错误 - conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); - //得到输入流 - InputStream inputStream = conn.getInputStream(); - //获取自己数组 - byte[] getData = readInputStream(inputStream); - File saveDir = new File(savePath); - if(!saveDir.exists()){ - saveDir.mkdir(); + public static Map downLoadFromUrl(String urlStr, String fileName, String savePath){ + + Map resmap = new HashMap<>(); + Map map = checkURLStatusCode(urlStr); + if(map.get("Check").equals("false")){ +// StatusCode + resmap.put("res",false); + resmap.put("StatusCode",map.get("StatusCode")); + return resmap; } - File file = new File(saveDir+File.separator+fileName); - FileOutputStream fos = new FileOutputStream(file); - fos.write(getData); - if(fos!=null){ - fos.close(); + try { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + //设置超时间为3秒 + conn.setConnectTimeout(5*1000); + //防止屏蔽程序抓取而返回403错误 + conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); + + //得到输入流 + InputStream inputStream = conn.getInputStream(); + //获取自己数组 + byte[] getData = readInputStream(inputStream); + File saveDir = new File(savePath); + if(!saveDir.exists()){ + saveDir.mkdir(); + } + File file = new File(saveDir+File.separator+fileName); + FileOutputStream fos = new FileOutputStream(file); + fos.write(getData); + if(fos!=null){ + fos.close(); + } + if(inputStream!=null){ + inputStream.close(); + } + //下载并且保存成功后 判断格式 如果不是图像格式 就删除 +// + if(new File(saveDir+File.separator+fileName).exists()){ + Msg msg = TypeDict.FileMiME(file,null); + if(msg.getCode().equals("200")){ + File f = new File(saveDir+File.separator+fileName); + String imgPath = saveDir+File.separator+fileName+"."+(msg.getData().toString().replace("image/","")); + f.renameTo(new File(imgPath)); + resmap.put("res",true); + resmap.put("imgPath",imgPath); + }else{ + new File(saveDir+File.separator+fileName).delete(); + resmap.put("res",false); + resmap.put("StatusCode","110403"); + } + }else{ + resmap.put("res",false); + resmap.put("StatusCode","500"); + } + + + return resmap; + }catch (Exception e){ + e.printStackTrace(); + resmap.put("res",false); + resmap.put("StatusCode","500"); + return resmap; } - if(inputStream!=null){ - inputStream.close(); - } - return true; } + + /** * 从输入流中获取字节数组 * @param inputStream diff --git a/src/main/java/cn/hellohao/utils/LocUpdateImg.java b/src/main/java/cn/hellohao/utils/LocUpdateImg.java index b086fb2..59d9efd 100644 --- a/src/main/java/cn/hellohao/utils/LocUpdateImg.java +++ b/src/main/java/cn/hellohao/utils/LocUpdateImg.java @@ -1,7 +1,9 @@ package cn.hellohao.utils; +import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.ReturnImage; import cn.hellohao.pojo.UploadConfig; +import cn.hellohao.service.impl.KeysServiceImpl; import org.springframework.web.multipart.MultipartFile; import java.io.*; @@ -11,127 +13,57 @@ import java.util.Map; import java.util.UUID; public class LocUpdateImg { - public static void deleteLOCImg(String imagename){ - String filePath =File.separator + "HellohaoData" + File.separator+imagename; - File file = new File(filePath); - file.delete(); + public static boolean deleteLOCImg(String imagename){ + boolean isDele = false; + try { + String filePath =File.separator + "HellohaoData" + File.separator+imagename; + File file = new File(filePath); + isDele = file.delete(); + }catch (Exception e){ + e.printStackTrace(); + isDele = false; + } + return isDele; } - public static Map ImageuploadLOC(Map fileMap, String username, - Map fileMap2,Integer setday) throws Exception { - String filePath =File.separator + "HellohaoData" + File.separator; - if(fileMap2==null){ - File file = null; - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = "TOIMG"+UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - // 上传文件流。 - System.out.println("待上传的图片:"+username + File.separator + uuid+times + "N." + entry.getKey()); - File dest = new File(filePath + username + File.separator+ uuid+times + "N." + entry.getKey()); - File temppath = new File(filePath + username+ File.separator ); - if (!dest.getParentFile().exists()) { - dest.getParentFile().mkdirs(); - } - try { - MultipartFile multipartFile = entry.getValue(); - //FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream(); - InputStream fileInputStream = (InputStream)multipartFile.getInputStream(); - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest)); - byte[] bs = new byte[1024]; - int len; - while ((len = fileInputStream.read(bs)) != -1) { - bos.write(bs, 0, len); - } - bos.flush(); - bos.close(); - ReturnImage returnImage = new ReturnImage(); - returnImage.setImgname(username + "/" +uuid+times + "N." + entry.getKey());//entry.getValue().getOriginalFilename() - returnImage.setImgurl(username + "/" + uuid+times + "N." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "N." + entry.getKey() + "|" + deleimg + "|" + "5"); - } - } catch (IOException e) { - e.printStackTrace(); - System.err.println("上传失败"); - } - } - return ImgUrl; - }else{ - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap2.entrySet()) { - String uuid = "TOIMG"+UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - String oldfilePath = entry.getValue(); - String newfilePath = File.separator + "HellohaoData" + File.separator + username + File.separator+ uuid+times + "N." + entry.getKey(); - String tempfilePath = File.separator + "HellohaoData" + File.separator + username+ File.separator ; - File file = new File(oldfilePath); - File targetFile =new File(tempfilePath); - if(!targetFile.getParentFile().exists()) { - targetFile.mkdirs(); - } - file.renameTo(new File(newfilePath)); - //采用数据流模式上传文件(节省内存),自动创建父级目录 - ReturnImage returnImage = new ReturnImage(); - //username + "/" + uuid+times + "." + entry.getKey() - returnImage.setImgurl(username + "/" + uuid+times + "N." + entry.getKey()); - ImgUrl.put( returnImage, ImgUrlUtil.getFileSize2(new File(newfilePath))); - if(setday>0) { - String deleimg = DateUtils.plusDay(setday); - DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "5"); - } - } - return ImgUrl; - } - } - - /** - * 客户端接口 - * */ - public static Map clientLocUpdateImg(Map fileMap, String username, UploadConfig uploadConfig) { + public static ReturnImage ImageuploadLOC(Map fileMap, String username,Integer keyID) throws Exception { + KeysServiceImpl keysService = SpringContextHolder.getBean(KeysServiceImpl.class); + final Keys key = keysService.selectKeys(keyID); + ReturnImage returnImage = new ReturnImage(); String filePath =File.separator + "HellohaoData" + File.separator; File file = null; - Map ImgUrl = new HashMap<>(); - for (Map.Entry entry : fileMap.entrySet()) { - String uuid = "TOIMG"+UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位 - java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss"); - String times = format1.format(new Date()); - System.out.println("待上传的图片:"+username + "/" + uuid+times + "N." + entry.getKey()); - ReturnImage returnImage = new ReturnImage(); - if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){ - File dest = new File(filePath + username + File.separator+ uuid+times + "N." + entry.getKey()); - if (!dest.getParentFile().exists()) { - dest.getParentFile().mkdirs(); + for (Map.Entry entry : fileMap.entrySet()) { + String ShortUID = SetText.getShortUuid(); + System.out.println("待上传的图片:"+username + File.separator + ShortUID + "." + entry.getKey()); + File dest = new File(filePath + username + File.separator+ ShortUID + "." + entry.getKey()); + File temppath = new File(filePath + username+ File.separator ); + if (!dest.getParentFile().exists()) { + dest.getParentFile().mkdirs(); + } + try { + InputStream fileInputStream = new FileInputStream(entry.getValue()); + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest)); + byte[] bs = new byte[1024]; + int len; + while ((len = fileInputStream.read(bs)) != -1) { + bos.write(bs, 0, len); } - try { - MultipartFile multipartFile = entry.getValue(); - FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream(); - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest)); - byte[] bs = new byte[1024]; - int len; - while ((len = fileInputStream.read(bs)) != -1) { - bos.write(bs, 0, len); - } - bos.flush(); - bos.close(); - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl(username + "/" + uuid+times + "N." + entry.getKey()); - ImgUrl.put(returnImage, (int) (entry.getValue().getSize())/1024); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("上传失败"); - } - }else{ - returnImage.setImgname(entry.getValue().getOriginalFilename()); - returnImage.setImgurl("文件超出系统设定大小,不得超过"); - ImgUrl.put(returnImage,-1); + bos.flush(); + bos.close(); + returnImage.setUid(ShortUID); + returnImage.setImgname(username + "/" +ShortUID + "." + entry.getKey());//entry.getValue().getOriginalFilename() + returnImage.setImgurl(key.getRequestAddress() +"/ota/"+username + "/" + ShortUID + "." + entry.getKey()); + returnImage.setImgSize(entry.getValue().length()); + returnImage.setCode("200"); + + } catch (IOException e) { + e.printStackTrace(); + returnImage.setCode("500"); + System.err.println("上传失败"); } } - return ImgUrl; + return returnImage; } + } diff --git a/src/main/java/cn/hellohao/utils/NewSendEmail.java b/src/main/java/cn/hellohao/utils/NewSendEmail.java new file mode 100644 index 0000000..3cd4a8d --- /dev/null +++ b/src/main/java/cn/hellohao/utils/NewSendEmail.java @@ -0,0 +1,171 @@ +package cn.hellohao.utils; + +import cn.hellohao.pojo.Config; +import cn.hellohao.pojo.EmailConfig; +import cn.hellohao.pojo.Msg; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.HexUtil; +import com.mitchellbosecke.pebble.PebbleEngine; +import com.mitchellbosecke.pebble.template.PebbleTemplate; +import io.github.biezhi.ome.OhMyEmail; +import org.springframework.core.io.ClassPathResource; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +public class NewSendEmail { + + public static void initialEmail(EmailConfig emailConfig) { +// Properties p = new Properties(); +// p.setProperty("mail.smtp.auth", "true"); +// p.setProperty("mail.smtp.host", emailConfig.getEmailurl()); +// p.setProperty("mail.smtp.port", emailConfig.getPort()); +// p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); + + + } + + public static Integer sendEmail(EmailConfig emailConfig, String username, String uid, String toEmail, Config config) { + + Properties props = new Properties(); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.ssl.enable", "true"); + props.put("mail.debug", "false"); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.debug", "false"); + props.put("mail.smtp.timeout", "20000"); + props.put("mail.smtp.port", emailConfig.getPort());//465 25 + props.put("mail.smtp.host", emailConfig.getEmailurl()); + // 配置一次即可,可以配置为静态方法 +// OhMyEmail.config(OhMyEmail.SMTP_QQ(false), "xxxx@qq.com", "your@password"); + OhMyEmail.config(props, emailConfig.getEmails(), emailConfig.getEmailkey()); + + String webname=config.getWebname(); + String domain = config.getDomain(); + try { + //生成模板 + PebbleEngine engine = new PebbleEngine.Builder().build(); + ClassPathResource classPathResource = new ClassPathResource("emailTemplate/emailRegister.html"); + PebbleTemplate compiledTemplate = engine.getTemplate(classPathResource.getPath()); + Map context = new HashMap<>(); + context.put("username", username); + context.put("webname", webname); + context.put("url", domain+"/user/activation?activation="+uid+"&username=" + username ); + Writer writer = new StringWriter(); + compiledTemplate.evaluate(writer, context); + String output = writer.toString(); + OhMyEmail.subject(webname+"账号激活") + .from(webname) + .to(toEmail) + .html(output) + .send(); + return 1; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + public static Msg sendTestEmail(EmailConfig emailConfig, String toEmail) { + Msg msg = new Msg(); + Properties props = new Properties(); + try { + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.ssl.enable", "true"); + props.put("mail.debug", "false"); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.debug", "false"); + props.put("mail.smtp.timeout", "20000"); + props.put("mail.smtp.port", emailConfig.getPort());//465 25 + props.put("mail.smtp.host", emailConfig.getEmailurl()); + OhMyEmail.config(props, emailConfig.getEmails(), emailConfig.getEmailkey()); + String webname="Hellohao图像托管程序"; + OhMyEmail.subject("Hellohao图像托管程序邮箱配置测试") + .from(webname) + .to(toEmail) + .html("

这是一条测试邮件,当您收到此邮件证明测试成功了

") + .send(); + msg.setInfo("发送邮件指令已执行,请自行前往收信箱或垃圾箱查看是否收到测试邮件"); + return msg; + } catch (Exception e) { + e.printStackTrace(); + System.out.println(e.getMessage()); + msg.setCode("110500"); + msg.setInfo(e.getMessage()); + return msg; + } + } + + + public static Integer sendEmailFindPass(EmailConfig emailConfig,String username, String uid, String toEmail, Config config) { + Properties props = new Properties(); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.ssl.enable", "true"); + props.put("mail.debug", "false"); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.debug", "false"); + props.put("mail.smtp.timeout", "20000"); + props.put("mail.smtp.port", emailConfig.getPort());//465 25 + props.put("mail.smtp.host", emailConfig.getEmailurl()); + // 配置一次即可,可以配置为静态方法 +// OhMyEmail.config(OhMyEmail.SMTP_QQ(false), "xxxx@qq.com", "your@password"); + OhMyEmail.config(props, emailConfig.getEmails(), emailConfig.getEmailkey()); + + String webname=config.getWebname(); + String domain = config.getDomain(); + String new_pass = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,10); + try { + //生成模板 + PebbleEngine engine = new PebbleEngine.Builder().build(); + ClassPathResource classPathResource = new ClassPathResource("emailTemplate/emailFindPass.html"); + PebbleTemplate compiledTemplate = engine.getTemplate(classPathResource.getPath()); + Map context = new HashMap<>(); + context.put("username", username); + context.put("webname", webname); + context.put("new_pass", new_pass); + context.put("url",domain+"/user/retrieve?activation=" + uid+"&cip="+ HexUtil.encodeHexStr(new_pass, CharsetUtil.CHARSET_UTF_8)); + Writer writer = new StringWriter(); + compiledTemplate.evaluate(writer, context); + String output = writer.toString(); + OhMyEmail.subject(webname+"密码重置") + .from(webname) + .to(toEmail) + .html(output) + .send(); + return 1; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + + public static void main(String[] args)throws Exception { + + Properties props = new Properties(); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.ssl.enable", "true"); + props.put("mail.debug", "false"); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.debug", "false"); + props.put("mail.smtp.timeout", "20000"); + props.put("mail.smtp.port", "25");//465 25 + props.put("mail.smtp.host", "smtpdm.aliyun.com"); + + // 配置一次即可,可以配置为静态方法 +// OhMyEmail.config(OhMyEmail.SMTP_QQ(false), "xxxx@qq.com", "your@password"); + OhMyEmail.config(props, "hellohao@wwery.com", "TianShiHao1995"); + OhMyEmail.subject("账号激活邮件测试") + .from("hahhaha") + .to("923453645@qq.com") + .html("hellohao") + .send(); + + } + + +} diff --git a/src/main/java/cn/hellohao/utils/SendEmail.java b/src/main/java/cn/hellohao/utils/SendEmail.java deleted file mode 100644 index f9a40fc..0000000 --- a/src/main/java/cn/hellohao/utils/SendEmail.java +++ /dev/null @@ -1,93 +0,0 @@ -package cn.hellohao.utils; - -import cn.hellohao.pojo.Config; -import cn.hellohao.pojo.EmailConfig; -import javax.mail.*; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.Properties; - -public class SendEmail { - - public static MimeMessage Emails(EmailConfig emailConfig) { - Properties p = new Properties(); - p.setProperty("mail.smtp.auth", "true"); - p.setProperty("mail.smtp.host", emailConfig.getEmailurl()); - p.setProperty("mail.smtp.port", emailConfig.getPort()); - p.setProperty("mail.smtp.socketFactory.port", emailConfig.getPort()); - p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); - //p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY"); - - Session session = Session.getInstance(p, new Authenticator() { - // 设置认证账户信息 - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(emailConfig.getEmails(), emailConfig.getEmailkey()); - } - }); - session.setDebug(true); - MimeMessage message = new MimeMessage(session); - return message; - } - - public static Integer sendEmail(MimeMessage message, String username, String Url, String email, EmailConfig emailConfig, Config config) { - String webname=config.getWebname(); - String domain = config.getDomain(); - String texts = "

你正在注册【"+webname+"】,点击下方链接进行激活:


"+domain+"/user/activation.do?activation=" + Url + "&username=" + username + ""; - String body = "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "
\n" + - "
\n" + - "
\n" + - "
\n" + - " 账号激活 \n" + - " \n" + - "
\n" + - " \n" + - " \n" + - " \n" + - "
\n" + - "
\n" + - "
\n" + - "
\n" + - "
您正在注册"+webname+"
\n" + - "

点击  激活链接  进行账号激活

\n" + - "
\n" + - "
\n" + - "
\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - try { - // 发件人 - message.setFrom(new InternetAddress(emailConfig.getEmails(), emailConfig.getEmailname(), "UTF-8")); - // 收件人和抄送人 - message.setRecipients(Message.RecipientType.TO, email); - message.setSubject(emailConfig.getEmailname()+"账号激活");//标题 - message.setContent(texts, "text/html;charset=UTF-8");//内容 - message.setSentDate(new Date()); - message.saveChanges(); - Transport.send(message); - return 1; - } catch (MessagingException e) { - e.printStackTrace(); - return 0; - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return 0; - } - } - - -} diff --git a/src/main/java/cn/hellohao/utils/SetFiles.java b/src/main/java/cn/hellohao/utils/SetFiles.java index a040dda..71738b3 100644 --- a/src/main/java/cn/hellohao/utils/SetFiles.java +++ b/src/main/java/cn/hellohao/utils/SetFiles.java @@ -3,6 +3,7 @@ package cn.hellohao.utils; import org.springframework.web.multipart.MultipartFile; import java.io.*; +import java.text.DecimalFormat; public class SetFiles { // 转换文件方法 @@ -54,7 +55,24 @@ public class SetFiles { return file; } - + //文件大小单位转换 + public static String readableFileSize(long fileS) { + if(fileS==0){ + return "0B"; + } + DecimalFormat df = new DecimalFormat("#.00"); + String fileSizeString = ""; + if (fileS < 1024) { + fileSizeString = df.format((double) fileS) + "B"; + } else if (fileS < 1048576) { + fileSizeString = df.format((double) fileS / 1024) + "K"; + } else if (fileS < 1073741824) { + fileSizeString = df.format((double) fileS / 1048576) + "M"; + } else { + fileSizeString = df.format((double) fileS / 1073741824) + "G"; + } + return fileSizeString; + } diff --git a/src/main/java/cn/hellohao/utils/SetText.java b/src/main/java/cn/hellohao/utils/SetText.java index fbef67d..1a89d3f 100644 --- a/src/main/java/cn/hellohao/utils/SetText.java +++ b/src/main/java/cn/hellohao/utils/SetText.java @@ -1,5 +1,9 @@ package cn.hellohao.utils; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class SetText { public static String getSubString(String text, String left, String right) { String result = ""; @@ -21,4 +25,47 @@ public class SetText { result = text.substring(zLen, yLen); return result; } + + //获取8位短uuid + public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", + "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", + "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", + "U", "V", "W", "X", "Y", "Z" }; + + public static String getShortUuid() { + StringBuffer shortBuffer = new StringBuffer(); + String uuid = UUID.randomUUID().toString().replace("-", ""); + for (int i = 0; i < 8; i++) { + String str = uuid.substring(i * 4, i * 4 + 4); + int x = Integer.parseInt(str, 16); + shortBuffer.append(chars[x % 0x3E]); + } + return shortBuffer.toString(); + } + + public static String get32UUID() { + String uuid = UUID.randomUUID().toString().trim().replaceAll("-", ""); + return uuid; + } + + /** + * 验证邮箱 + * @param email + * @return + */ + public static boolean checkEmail(String email) { + boolean flag = false; + try { + String check = "^\\w+@[a-zA-Z0-9]{2,10}(?:\\.[a-z]{2,4}){1,3}$"; + Pattern regex = Pattern.compile(check); + Matcher matcher = regex.matcher(email); + flag = matcher.matches(); + } catch (Exception e) { + flag = false; + } + return flag; + } + + } + diff --git a/src/main/java/cn/hellohao/utils/TypeDict.java b/src/main/java/cn/hellohao/utils/TypeDict.java index 8cbeb61..98d36fa 100644 --- a/src/main/java/cn/hellohao/utils/TypeDict.java +++ b/src/main/java/cn/hellohao/utils/TypeDict.java @@ -1,5 +1,8 @@ package cn.hellohao.utils; +import cn.hellohao.pojo.Msg; +import org.apache.tika.Tika; + import javax.imageio.ImageIO; import java.awt.*; import java.io.File; @@ -65,5 +68,29 @@ MIDI (mid),文件头:4D546864 } } + //apache大法 + public static Msg FileMiME(File file, String suffix){ + final Msg msg = new Msg(); + try { + Tika tika = new Tika(); + String fileType = tika.detect(file); + if (fileType != null && fileType.contains("/")) { + if(fileType.contains("image/")){ + msg.setData(fileType); + }else{ + //非图像类型 + msg.setCode("110602"); + msg.setInfo("该文件非图像文件,或不受支持"); + } + } + } catch (Exception e) { + System.err.println("这是一个图像类别鉴定的报错:161"); + msg.setCode("110603");//图像格式不受支持 + msg.setInfo("暂时不能上传该文件"); + } + return msg; + } + + } \ No newline at end of file diff --git a/src/main/java/cn/hellohao/utils/verifyCode/IVerifyCodeGen.java b/src/main/java/cn/hellohao/utils/verifyCode/IVerifyCodeGen.java new file mode 100644 index 0000000..8730b1b --- /dev/null +++ b/src/main/java/cn/hellohao/utils/verifyCode/IVerifyCodeGen.java @@ -0,0 +1,31 @@ +package cn.hellohao.utils.verifyCode; + +import java.io.IOException; +import java.io.OutputStream; + +/** +* 验证码生成接口 +*/ +public interface IVerifyCodeGen { + +/** +* 生成验证码并返回code,将图片写的os中 +* +* @param width +* @param height +* @param os +* @return +* @throws IOException +*/ +String generate(int width, int height, OutputStream os) throws IOException; + +/** +* 生成验证码对象 +* +* @param width +* @param height +* @return +* @throws IOException +*/ +VerifyCode generate(int width, int height) throws IOException; +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/utils/verifyCode/RandomUtils.java b/src/main/java/cn/hellohao/utils/verifyCode/RandomUtils.java new file mode 100644 index 0000000..37f2a46 --- /dev/null +++ b/src/main/java/cn/hellohao/utils/verifyCode/RandomUtils.java @@ -0,0 +1,48 @@ +package cn.hellohao.utils.verifyCode; + +import java.awt.*; +import java.util.Random; + +public class RandomUtils extends org.apache.commons.lang3.RandomUtils { + +private static final char[] CODE_SEQ = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', +'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', +'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' }; + +private static final char[] NUMBER_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; + +private static Random random = new Random(); + +public static String randomString(int length) { +StringBuilder sb = new StringBuilder(); +for (int i = 0; i < length; i++) { +sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)])); +} +return sb.toString(); +} + +public static String randomNumberString(int length) { +StringBuilder sb = new StringBuilder(); +for (int i = 0; i < length; i++) { +sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)])); +} +return sb.toString(); +} + +public static Color randomColor(int fc, int bc) { +int f = fc; +int b = bc; +Random random = new Random(); +if (f > 255) { +f = 255; +} +if (b > 255) { +b = 255; +} +return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f)); +} + +public static int nextInt(int bound) { +return random.nextInt(bound); +} +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/utils/verifyCode/SimpleCharVerifyCodeGenImpl.java b/src/main/java/cn/hellohao/utils/verifyCode/SimpleCharVerifyCodeGenImpl.java new file mode 100644 index 0000000..cff6df5 --- /dev/null +++ b/src/main/java/cn/hellohao/utils/verifyCode/SimpleCharVerifyCodeGenImpl.java @@ -0,0 +1,116 @@ +package cn.hellohao.utils.verifyCode; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Random; + +/** +* 验证码实现类 +*/ +public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen { + +private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class); + +private static final String[] FONT_TYPES = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" }; + +private static final int VALICATE_CODE_LENGTH = 4; + +/** +* 设置背景颜色及大小,干扰线 +* +* @param graphics +* @param width +* @param height +*/ +private static void fillBackground(Graphics graphics, int width, int height) { +// 填充背景 +graphics.setColor(Color.WHITE); +//设置矩形坐标x y 为0 +graphics.fillRect(0, 0, width, height); + +// 加入干扰线条 +for (int i = 0; i < 8; i++) { +//设置随机颜色算法参数 +graphics.setColor(RandomUtils.randomColor(40, 150)); +Random random = new Random(); +int x = random.nextInt(width); +int y = random.nextInt(height); +int x1 = random.nextInt(width); +int y1 = random.nextInt(height); +graphics.drawLine(x, y, x1, y1); +} +} + +/** +* 生成随机字符 +* +* @param width +* @param height +* @param os +* @return +* @throws IOException +*/ +@Override +public String generate(int width, int height, OutputStream os) throws IOException { +BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); +Graphics graphics = image.getGraphics(); +fillBackground(graphics, width, height); +String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH); +createCharacter(graphics, randomStr); +graphics.dispose(); +//设置JPEG格式 +ImageIO.write(image, "JPEG", os); +return randomStr; +} + +/** +* 验证码生成 +* +* @param width +* @param height +* @return +*/ +@Override +public VerifyCode generate(int width, int height) { +VerifyCode verifyCode = null; +try ( +//将流的初始化放到这里就不需要手动关闭流 +ByteArrayOutputStream baos = new ByteArrayOutputStream(); +) { +String code = generate(width, height, baos); +verifyCode = new VerifyCode(); +verifyCode.setCode(code); +verifyCode.setImgBytes(baos.toByteArray()); +} catch (IOException e) { +logger.error(e.getMessage(), e); +verifyCode = null; +} +return verifyCode; +} + +/** +* 设置字符颜色大小 +* +* @param g +* @param randomStr +*/ +private void createCharacter(Graphics g, String randomStr) { +char[] charArray = randomStr.toCharArray(); +for (int i = 0; i < charArray.length; i++) { +//设置RGB颜色算法参数 +g.setColor(new Color(50 + RandomUtils.nextInt(100), +50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100))); +//设置字体大小,类型 +g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26)); +//设置x y 坐标 +g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8)); +} +} +} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/utils/verifyCode/VerifyCode.java b/src/main/java/cn/hellohao/utils/verifyCode/VerifyCode.java new file mode 100644 index 0000000..860de13 --- /dev/null +++ b/src/main/java/cn/hellohao/utils/verifyCode/VerifyCode.java @@ -0,0 +1,29 @@ +package cn.hellohao.utils.verifyCode; + +/** +* 验证码类 +*/ +public class VerifyCode { + private String code; + private byte[] imgBytes; + private long expireTime; + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + public byte[] getImgBytes() { + return imgBytes; + } + public void setImgBytes(byte[] imgBytes) { + this.imgBytes = imgBytes; + } + public long getExpireTime() { + return expireTime; + } + public void setExpireTime(long expireTime) { + this.expireTime = expireTime; + } + +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ff65c0c..1b3e09f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,11 +3,11 @@ spring.datasource.username=root #数据库密码test spring.datasource.password=root #数据库链接地址 -spring.datasource.url=jdbc:mysql://localhost:3306/picturebed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 +spring.datasource.url=jdbc:mysql://localhost:3306/tbed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 #端口 -server.port=8088 -#鉴黄周期表达式 下方表达式为每天四点半执行0 30 04 * * ? -Expression=0 30 04 * * ? +server.port=8089 +#前端域名需要带协议头http(s):// +CROS_ALLOWED_ORIGINS=http://localhost:8080 #下边的配置项不需要修改。 diff --git a/src/main/resources/emailTemplate/emailFindPass.html b/src/main/resources/emailTemplate/emailFindPass.html new file mode 100644 index 0000000..527698a --- /dev/null +++ b/src/main/resources/emailTemplate/emailFindPass.html @@ -0,0 +1,12 @@ +
+

您正在找回{{ webname }}的登录密码

+

点击下方链接进行密码重置:

+

{{url}}

+

注意:验证成功后系统会将您的密码恢复为:{{new_pass}},请及时登录后台更改。

+

如果您的 email 程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。

+

若非本人操作,无需理会!

+

+

-----------------------

+

+

(这是一封自动产生的email,请勿回复。)

+
\ No newline at end of file diff --git a/src/main/resources/emailTemplate/emailRegister.html b/src/main/resources/emailTemplate/emailRegister.html new file mode 100644 index 0000000..31db102 --- /dev/null +++ b/src/main/resources/emailTemplate/emailRegister.html @@ -0,0 +1,13 @@ +
+

亲爱的{{ username }}, 欢迎加入 {{webname}} !

+

您离正常登录只有一步之遥啦。

+

请点击一下链接验证并激活账号:

+

{{url}}

+

如果您的 email 程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。

+

若非本人操作,请勿理会!

+

希望您在 {{webname}} 系统度过快乐的时光!

+

+

-----------------------

+

+

(这是一封自动产生的email,请勿回复。)

+
\ No newline at end of file diff --git a/src/main/resources/mapper/AlbumMapper.xml b/src/main/resources/mapper/AlbumMapper.xml index 0a4e5cd..b644e49 100644 --- a/src/main/resources/mapper/AlbumMapper.xml +++ b/src/main/resources/mapper/AlbumMapper.xml @@ -29,7 +29,6 @@ + + + \ No newline at end of file diff --git a/src/main/resources/mapper/ConfigMapper.xml b/src/main/resources/mapper/ConfigMapper.xml index 2bb8cad..f98e98b 100644 --- a/src/main/resources/mapper/ConfigMapper.xml +++ b/src/main/resources/mapper/ConfigMapper.xml @@ -60,7 +60,15 @@ `theme` = #{theme}, - + + websubtitle = #{websubtitle}, + + + logo = #{logo}, + + + aboutinfo = #{aboutinfo}, + diff --git a/src/main/resources/mapper/GroupMapper.xml b/src/main/resources/mapper/GroupMapper.xml index dbfe857..4b091a9 100644 --- a/src/main/resources/mapper/GroupMapper.xml +++ b/src/main/resources/mapper/GroupMapper.xml @@ -22,6 +22,14 @@ insert into `group` (id,groupname,keyid) values (null,#{groupname},#{keyid}) + + delete from `group` where id=#{id} @@ -30,5 +38,12 @@ UPDATE `group` SET groupname=#{groupname},keyid=#{keyid} where id = #{id}; + \ No newline at end of file diff --git a/src/main/resources/mapper/ImgMapper.xml b/src/main/resources/mapper/ImgMapper.xml index 9a90eaf..ce995d0 100644 --- a/src/main/resources/mapper/ImgMapper.xml +++ b/src/main/resources/mapper/ImgMapper.xml @@ -15,7 +15,13 @@ a.source, a.imgtype, a.explains, - a.md5key + a.md5key, + a.imguid, + a.shortlink, + a.format, + a.about, + a.great, + a.violation FROM imgdata a LEFT JOIN user b ON a.userid = b.id @@ -99,7 +105,7 @@ SELECT * from imgdata WHERE updatetime>=#{time} - SELECT sum(sizes) as sizes FROM `imgdata` where userid = #{userid} @@ -114,9 +120,52 @@ - + + + + + + + + update imgdata set great = (great+1) where id = #{id} + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/ImgTempMapper.xml b/src/main/resources/mapper/ImgTempMapper.xml new file mode 100644 index 0000000..64dc334 --- /dev/null +++ b/src/main/resources/mapper/ImgTempMapper.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + id,imguid,deltime + + + + UPDATE `user` + + + `great` = great+1, + + + + where imguid=#{imguid} + + + + + + + + DELETE imgtemp,imgdata FROM imgtemp LEFT JOIN imgdata ON imgtemp.imguid = imgdata.imguid + WHERE imgdata.imguid =#{imguid} + + + + + + + insert into `imgtemp` (id,imguid,`deltime`) + values (null,#{imguid},#{deltime}) + + + + diff --git a/src/main/resources/mapper/ImgreviewMapper.xml b/src/main/resources/mapper/ImgreviewMapper.xml index 19205a8..978acb6 100644 --- a/src/main/resources/mapper/ImgreviewMapper.xml +++ b/src/main/resources/mapper/ImgreviewMapper.xml @@ -21,6 +21,15 @@ from imgreview where id = #{id,jdbcType=INTEGER} + + + delete from imgreview diff --git a/src/main/resources/mapper/KeysMapper.xml b/src/main/resources/mapper/KeysMapper.xml index 5419708..83c6eb2 100644 --- a/src/main/resources/mapper/KeysMapper.xml +++ b/src/main/resources/mapper/KeysMapper.xml @@ -10,7 +10,7 @@ FROM `keys` WHERE - storageType = #{storageType} + id = #{id} diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml index b65d446..ff89ec6 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -47,8 +47,8 @@ - - SELECT id, username, email, @@ -60,7 +60,17 @@ memory, groupid FROM user - WHERE email = #{email} + + + and id = #{id} + + + and email = #{email} + + + and uid = #{uid} + + SELECT - * + id, + username, + email, + (select from_base64(password)) as password, + birthder, + LEVEL, + uid, + isok, + ceil((memory/1024/1024)) as memory, + groupid, + (select groupname from `group` where id = groupid) as groupname, FROM user + where + 1=1 - where - CONCAT( + and CONCAT( username, email ) LIKE '%${username}%'