diff --git a/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java b/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java index 34c95b9..2480366 100644 --- a/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java +++ b/src/main/java/cn/hellohao/auth/filter/SubjectFilter.java @@ -25,6 +25,7 @@ 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; @@ -72,12 +73,15 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(userData.getEmail(),userData.getPassword()); tokenOBJ.setRememberMe(true); + //执行登录方法,如果没有异常,说明登录成功 subject.login(tokenOBJ); SecurityUtils.getSubject().getSession().setTimeout(3600000); User loginUser = (User) SecurityUtils.getSubject().getPrincipal(); } } } + +// String token = httpServletRequest.getHeader("Authorization"); JSONObject jsonObject = JWTUtil.checkToken(token); if(!jsonObject.getBoolean("check")){ if(!serviceName.contains("admin") || serviceName.contains("admin/client")){ @@ -96,6 +100,7 @@ public class SubjectFilter extends BasicHttpAuthenticationFilter { subject.login(tokenOBJ); SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时 } catch (Exception e) { +// System.err.println("拦截器,登录失败,false"); this.CODE = "403"; return false; } diff --git a/src/main/java/cn/hellohao/auth/shiro/UserRealm.java b/src/main/java/cn/hellohao/auth/shiro/UserRealm.java index 9fd5480..5bfb3e4 100644 --- a/src/main/java/cn/hellohao/auth/shiro/UserRealm.java +++ b/src/main/java/cn/hellohao/auth/shiro/UserRealm.java @@ -51,6 +51,7 @@ public class UserRealm extends AuthorizingRealm { if(u==null){ return null; } + //密码认证(防止泄露,不需要我们做) return new SimpleAuthenticationInfo(u,u.getPassword(),""); } } diff --git a/src/main/java/cn/hellohao/controller/AdminController.java b/src/main/java/cn/hellohao/controller/AdminController.java index a7ddb77..bdcf574 100644 --- a/src/main/java/cn/hellohao/controller/AdminController.java +++ b/src/main/java/cn/hellohao/controller/AdminController.java @@ -4,9 +4,14 @@ import cn.hellohao.config.SysName; import cn.hellohao.pojo.*; import cn.hellohao.pojo.vo.PageResultBean; import cn.hellohao.service.*; -import cn.hellohao.service.impl.*; -import cn.hellohao.utils.*; +import cn.hellohao.service.impl.AlbumServiceImpl; +import cn.hellohao.service.impl.UserServiceImpl; +import cn.hellohao.service.impl.deleImages; +import cn.hellohao.utils.Base64Encryption; +import cn.hellohao.utils.SetFiles; +import cn.hellohao.utils.SetText; import cn.hellohao.utils.progress.MyProgress; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageHelper; @@ -15,11 +20,17 @@ 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.web.bind.annotation.*; -import javax.servlet.http.HttpSession; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; /** * @author Hellohao @@ -30,25 +41,16 @@ import java.util.*; @RequestMapping("/admin") public class AdminController { - @Autowired - private ImgService imgService; - @Autowired - private KeysService keysService; - @Autowired - private UserServiceImpl userService; - @Autowired - private ImgreviewService imgreviewService; - @Autowired - private UploadConfigService uploadConfigService; - @Autowired - private CodeService codeService; - @Autowired - private AlbumService albumService; - @Autowired - AlbumServiceImpl albumServiceI; - @Autowired - private deleImages deleimages; - + @Autowired private ImgService imgService; + @Autowired private KeysService keysService; + @Autowired private UserServiceImpl userService; + @Autowired private ImgreviewService imgreviewService; + @Autowired private UploadConfigService uploadConfigService; + @Autowired private CodeService codeService; + @Autowired private AlbumService albumService; + @Autowired AlbumServiceImpl albumServiceI; + @Autowired private deleImages deleimages; + @Autowired private IRedisService iRedisService; @PostMapping(value = "/overviewData") @ResponseBody @@ -56,7 +58,7 @@ public class AdminController { Msg msg = new Msg(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); - user = userService.getUsers(user); + user = userService.getUsers(user); JSONObject jsonObject = new JSONObject(); UploadConfig uploadConfig = uploadConfigService.getUpdateConfig(); Imgreview imgreview = imgreviewService.selectByPrimaryKey(1); @@ -66,45 +68,51 @@ public class AdminController { jsonObject.put("myImgTotal", imgService.countimg(user.getId())); jsonObject.put("myAlbumTitle", albumService.selectAlbumCount(user.getId())); 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{ - Double aDouble = Double.valueOf(String.format("%.2f", (((double)usermemory/(double)memory)*100))); - if(aDouble>=999){ - jsonObject.put("myMemory",999); - }else{ - jsonObject.put("myMemory",aDouble); + Long usermemory = + imgService.getusermemory(user.getId()) == null + ? 0L + : imgService.getusermemory(user.getId()); + if (memory == 0) { + jsonObject.put("myMemory", "无容量"); + } else { + Double aDouble = + Double.valueOf(String.format("%.2f", (((double) usermemory / (double) memory) * 100))); + if (aDouble >= 999) { + jsonObject.put("myMemory", 999); + } else { + jsonObject.put("myMemory", aDouble); } } - jsonObject.put("myMemorySum",SetFiles.readableFileSize(memory)); - if(user.getLevel()>1){ + jsonObject.put("myMemorySum", SetFiles.readableFileSize(memory)); + if (user.getLevel() > 1) { ok = "true"; - jsonObject.put("imgTotal", imgService.counts(null) ); + jsonObject.put("imgTotal", imgService.counts(null)); jsonObject.put("userTotal", userService.getUserTotal()); jsonObject.put("ViolationImgTotal", imgreview.getCount()); - jsonObject.put("ViolationSwitch", isImgreviewOK==null?0:isImgreviewOK.getId()); + jsonObject.put("ViolationSwitch", isImgreviewOK == null ? 0 : isImgreviewOK.getId()); jsonObject.put("VisitorUpload", uploadConfig.getIsupdate()); - jsonObject.put("VisitorMemory", SetFiles.readableFileSize(Long.valueOf(uploadConfig.getVisitormemory())));//访客共大小 - if(uploadConfig.getIsupdate()!=1){ + jsonObject.put( + "VisitorMemory", + SetFiles.readableFileSize(Long.valueOf(uploadConfig.getVisitormemory()))); // 访客共大小 + if (uploadConfig.getIsupdate() != 1) { jsonObject.put("VisitorUpload", 0); - jsonObject.put("VisitorProportion",100.00); + jsonObject.put("VisitorProportion", 100.00); jsonObject.put("VisitorMemory", "禁用"); - }else{ - Long temp = imgService.getusermemory(0)==null?0:imgService.getusermemory(0); + } else { + Long temp = imgService.getusermemory(0) == null ? 0 : imgService.getusermemory(0); jsonObject.put("UsedMemory", (temp == null ? 0 : SetFiles.readableFileSize(temp))); - if(Long.valueOf(uploadConfig.getVisitormemory())==0){ - jsonObject.put("VisitorProportion",100.00); - }else if(Long.valueOf(uploadConfig.getVisitormemory())==-1){ - jsonObject.put("VisitorProportion",0); + if (Long.valueOf(uploadConfig.getVisitormemory()) == 0) { + jsonObject.put("VisitorProportion", 100.00); + } else if (Long.valueOf(uploadConfig.getVisitormemory()) == -1) { + jsonObject.put("VisitorProportion", 0); jsonObject.put("VisitorMemory", "无限"); - }else{ + } 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); + if (aDouble >= 999) { + jsonObject.put("VisitorProportion", 999); + } else { + jsonObject.put("VisitorProportion", aDouble); } } } @@ -117,40 +125,40 @@ public class AdminController { @PostMapping(value = "/SpaceExpansion") @ResponseBody public Msg SpaceExpansion(@RequestParam(value = "data", defaultValue = "") String data) { - final Msg msg = new Msg(); - final JSONObject jsonObject = JSONObject.parseObject(data); + Msg msg = new Msg(); + JSONObject jsonObject = JSONObject.parseObject(data); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); - user = userService.getUsers(user); - if(user.getIsok()==0){ + user = userService.getUsers(user); + if (user.getIsok() == 0) { msg.setCode("100403"); msg.setInfo("你暂时无法使用此功能"); return msg; } - if(null==user){ + if (null == user) { msg.setCode("100405"); msg.setInfo("用户信息不存在"); return msg; - }else{ + } else { long sizes = 0; Code code = codeService.selectCodekey(jsonObject.getString("code")); - if(null==code){ + if (null == code) { msg.setCode("100404"); msg.setInfo("扩容码不存在,请重新填写"); return msg; } Long userMemory = Long.valueOf(user.getMemory()); - sizes = Long.valueOf(code.getValue())+ userMemory; + sizes = Long.valueOf(code.getValue()) + userMemory; User newMemoryUser = new User(); newMemoryUser.setMemory(Long.toString(sizes)); newMemoryUser.setId(user.getId()); - userService.usersetmemory(newMemoryUser,jsonObject.getString("code")); - msg.setInfo("你已成功扩容"+SetFiles.readableFileSize(sizes)); + userService.usersetmemory(newMemoryUser, jsonObject.getString("code")); + msg.setInfo("你已成功扩容" + SetFiles.readableFileSize(sizes)); return msg; } } - @PostMapping(value={"/setImgFileName","/client/setImgFileName"}) + @PostMapping(value = {"/setImgFileName", "/client/setImgFileName"}) @ResponseBody public Msg setImgFileName(@RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); @@ -162,7 +170,7 @@ public class AdminController { images.setIdname(name.replaceAll(" ", "")); images.setImgname(imgname); imgService.setImg(images); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); msg.setCode("500"); } @@ -173,18 +181,18 @@ public class AdminController { @ResponseBody public Msg getRecently() { Msg msg = new Msg(); - final JSONObject jsonObject = new JSONObject(); + 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())); + 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){ + } catch (Exception e) { e.printStackTrace(); msg.setInfo("系统内部错误"); msg.setCode("500"); @@ -198,7 +206,7 @@ public class AdminController { @ResponseBody public Msg updateToken() { Msg msg = new Msg(); - try{ + try { Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); User u = new User(); @@ -208,63 +216,64 @@ public class AdminController { user.setToken(u.getToken()); msg.setData(u.getToken()); msg.setInfo("Token更新成功,即可生效"); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); msg.setCode("500"); msg.setInfo("Token更新失败"); } return msg; - } - @PostMapping("/getYyyy") + @PostMapping("/getYyyy") @ResponseBody - public Msg getYyyy(){ - final Msg msg = new Msg(); + public Msg getYyyy() { + 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())); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("allYyyy", imgService.getyyyy(null)); + jsonObject.put("userYyyy", imgService.getyyyy(u.getId())); msg.setData(jsonObject); return msg; } - @PostMapping("/getChart") + @PostMapping("/getChart") @ResponseBody - public Msg getChart(@RequestParam(value = "data", defaultValue = "") String data){ + 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){ + List list = null; + if (u.getLevel() > 1) { + if (type == 2) { Images images = new Images(); images.setYyyy(yyyy); list = imgService.countByM(images); - }else{ + } else { Images images = new Images(); images.setYyyy(yyyy); images.setUserid(u.getId()); list = imgService.countByM(images); } - }else{ + } 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 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()); + if (jobj.getInteger("id") == list.get(j).getMonthNum()) { + jobj.put("monthNum", getChinaes(list.get(j).getMonthNum())); + jobj.put("countNum", list.get(j).getCountNum()); } } } @@ -272,7 +281,7 @@ public class AdminController { return msg; } - @PostMapping("/getStorage") + @PostMapping("/getStorage") @ResponseBody public Msg getStorage() { Msg msg = new Msg(); @@ -281,7 +290,7 @@ public class AdminController { return msg; } - @PostMapping("/getStorageName") + @PostMapping("/getStorageName") @ResponseBody public Msg getStorageName() { Msg msg = new Msg(); @@ -290,7 +299,7 @@ public class AdminController { return msg; } - @PostMapping(value = {"/selectPhoto","/client/selectPhoto"}) + @PostMapping(value = {"/selectPhoto", "/client/selectPhoto"}) @ResponseBody public Msg selectPhoto(@RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); @@ -302,18 +311,18 @@ public class AdminController { Integer source = jsonObj.getInteger("source"); String starttime = jsonObj.getString("starttime"); String stoptime = jsonObj.getString("stoptime"); - String selectUserType = jsonObj.getString("selectUserType");//me/all + String selectUserType = jsonObj.getString("selectUserType"); // me/all String username = jsonObj.getString("username"); Integer selecttype = jsonObj.getInteger("selecttype"); boolean violation = jsonObj.getBoolean("violation"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - if(starttime!=null){ + if (starttime != null) { try { Date date1 = format.parse(starttime); - Date date2 = format.parse(stoptime==null?format.format(new Date()):stoptime); + Date date2 = format.parse(stoptime == null ? format.format(new Date()) : stoptime); int compareTo = date1.compareTo(date2); System.out.println(compareTo); - if(compareTo==1){ + if (compareTo == 1) { msg.setCode("110500"); msg.setInfo("起始日期不能大于结束日期"); return msg; @@ -327,44 +336,45 @@ public class AdminController { } Images img = new Images(); PageHelper.startPage(pageNum, pageSize); - if(violation){ + if (violation) { img.setViolation("true"); } img.setStarttime(starttime); img.setStoptime(stoptime); - if(subject.hasRole("admin")){ + if (subject.hasRole("admin")) { img.setSource(source); - if(selectUserType.equals("me")){ + if (selectUserType.equals("me")) { img.setUserid(user.getId()); img.setUsername(null); img.setSelecttype(null); - }else{ + } else { img.setUsername(username); img.setSelecttype(selecttype); } - }else{ + } else { img.setUserid(user.getId()); } List images = imgService.selectimg(img); PageInfo rolePageInfo = new PageInfo<>(images); - PageResultBean pageResultBean = new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList()); + PageResultBean pageResultBean = + new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList()); msg.setData(pageResultBean); return msg; } - @PostMapping(value = "/getUserInfo") + @PostMapping(value = "/getUserInfo") @ResponseBody public Msg getUserInfo() { Msg msg = new Msg(); try { Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); - final User u = new User(); + User u = new User(); u.setId(user.getId()); User userInfo = userService.getUsers(u); JSONObject jsonObject = new JSONObject(); - jsonObject.put("username",userInfo.getUsername()); - jsonObject.put("email",userInfo.getEmail()); + jsonObject.put("username", userInfo.getUsername()); + jsonObject.put("email", userInfo.getEmail()); msg.setData(jsonObject); } catch (Exception e) { e.printStackTrace(); @@ -374,7 +384,7 @@ public class AdminController { return msg; } - @PostMapping("/setUserInfo") + @PostMapping("/setUserInfo") @ResponseBody public Msg setUserInfo(@RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); @@ -386,44 +396,44 @@ public class AdminController { Subject subject = SecurityUtils.getSubject(); User u = (User) subject.getPrincipal(); User user = new User(); - if(!SetText.checkEmail(email)){ + if (!SetText.checkEmail(email)) { msg.setCode("110403"); msg.setInfo("邮箱格式不正确"); return msg; } String regex = "^\\w+$"; - if(username.length()>20 || !username.matches (regex)){ + if (username.length() > 20 || !username.matches(regex)) { msg.setCode("110403"); msg.setInfo("用户名不得超过20位字符"); return msg; } - if(subject.hasRole("admin")){ - final User userOld = new User(); + if (subject.hasRole("admin")) { + User userOld = new User(); userOld.setId(u.getId()); User userInfo = userService.getUsers(userOld); - if(!userInfo.getUsername().equals(username)){ + if (!userInfo.getUsername().equals(username)) { Integer countusername = userService.countusername(username); - if(countusername == 1 || !SysName.CheckSysName(username)){ + if (countusername == 1 || !SysName.CheckSysName(username)) { msg.setCode("110406"); msg.setInfo("此用户名已存在"); return msg; - }else { + } else { user.setUsername(username); } } - if(!userInfo.getEmail().equals(email)){ + if (!userInfo.getEmail().equals(email)) { Integer countmail = userService.countmail(email); - if(countmail == 1){ + if (countmail == 1) { msg.setCode("110407"); msg.setInfo("此邮箱已被注册"); return msg; - }else{ + } else { user.setEmail(email); } } user.setPassword(Base64Encryption.encryptBASE64(password.getBytes())); user.setUid(u.getUid()); - }else{ + } else { user.setPassword(Base64Encryption.encryptBASE64(password.getBytes())); user.setUid(u.getUid()); } @@ -437,26 +447,27 @@ public class AdminController { return msg; } - @PostMapping({"/deleImages","/client/deleImages"}) + @PostMapping({"/deleImages", "/client/deleImages"}) @ResponseBody - public Msg deleImages(HttpSession httpSession, @RequestParam(value = "data", defaultValue = "") String data) { + public Msg deleImages(@RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); JSONObject jsonObj = JSONObject.parseObject(data); - final String images = jsonObj.getString("images"); - if(images==null){ + String images = jsonObj.getString("images"); + String uuid = jsonObj.getString("uuid"); + if (images == null) { msg.setCode("404"); msg.setInfo("为获取到图像信息"); return msg; } - final String[] split = images.split(","); + String[] split = images.split(","); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); - if(null == user){ + if (null == user) { msg.setCode("500"); msg.setInfo("当前用户信息不存在"); return msg; } - if(split.length==0){ + if (split.length == 0) { msg.setCode("404"); msg.setInfo("为获取到图像信息"); return msg; @@ -465,93 +476,103 @@ public class AdminController { for (int i = 0; i < split.length; i++) { Integer imgid = Integer.valueOf(split[i]); Images image = imgService.selectByPrimaryKey(imgid); - if(!subject.hasRole("admin")){ - if(!image.getUserid().equals(user.getId())){ + if (!subject.hasRole("admin")) { + if (!image.getUserid().equals(user.getId())) { break; } } imgIds.add(imgid); } - if(imgIds.size()==0){ + if (imgIds.size() == 0) { msg.setCode("110404"); - }else{ - deleimages.dele(httpSession,imgIds.stream().toArray(Integer[]::new)); + } else { + deleimages.dele(uuid, imgIds.stream().toArray(Integer[]::new)); msg.setCode("200"); } return msg; } - @PostMapping({"/GetDelprogress","/client/GetDelprogress"}) + @PostMapping({"/GetDelprogress", "/client/GetDelprogress"}) @ResponseBody - public Msg GetDelprogress(HttpSession httpSession) { - Msg msg =new Msg(); - JSONObject jsonObject = new JSONObject(); - MyProgress myProgress = (MyProgress)httpSession.getAttribute("myProgressForDel"); - if(null==myProgress){ - jsonObject.put("succ",myProgress.getDelSuccessCount()); - jsonObject.put("errorlist",new ArrayList()); - jsonObject.put("oklist",new ArrayList()); - jsonObject.put("delover",false); - }else{ - jsonObject.put("succ",myProgress.getDelSuccessCount()); - jsonObject.put("errorlist",myProgress.getDelErrorImgListt()); - jsonObject.put("oklist",myProgress.getDelSuccessImgList()); - jsonObject.put("delover",myProgress.getDelOCT()); + public Msg GetDelprogress(@RequestParam(value = "data", defaultValue = "") String data) { + Msg msg = new Msg(); + try { + JSONObject jsonObj = JSONObject.parseObject(data); + String uuid = jsonObj.getString("uuid"); + JSONObject jsonObject = new JSONObject(); + MyProgress myProgress = + JSON.parseObject(iRedisService.getValue(uuid).toString(), MyProgress.class); + if (null == myProgress) { + jsonObject.put("succ", myProgress.getDelSuccessCount()); + jsonObject.put("errorlist", new ArrayList()); + jsonObject.put("oklist", new ArrayList()); + jsonObject.put("delover", false); + } else { + jsonObject.put("succ", myProgress.getDelSuccessCount()); + jsonObject.put("errorlist", myProgress.getDelErrorImgListt()); + jsonObject.put("oklist", myProgress.getDelSuccessImgList()); + jsonObject.put("delover", myProgress.getDelOCT()); + } + msg.setData(jsonObject); + if (myProgress.getDelOCT()==1) { + System.out.println("循环遍历的值:" + myProgress.getDelOCT()); + msg.setCode("100"); + } else { + msg.setCode("110666"); + msg.setInfo("正在执行"); + } + return msg; + } catch (Exception e) { + e.printStackTrace(); + msg.setCode("110500"); + msg.setInfo("正在执行过程中发生错误"); + return msg; } - msg.setData(jsonObject); - if(myProgress.getDelOCT()){ - System.out.println("循环遍历的值:"+myProgress.getDelOCT()); - msg.setCode("100"); - }else{ - msg.setCode("110666"); - msg.setInfo("正在执行"); - } - return msg; } - private static String getChinaes(int v){ + private static String getChinaes(int v) { String ch = ""; - switch(v){ - case 1 : + switch (v) { + case 1: ch = "一月"; - break; //可选 - case 2 : + break; // 可选 + case 2: ch = "二月"; - break; //可选 - case 3 : + break; // 可选 + case 3: ch = "三月"; - break; //可选 - case 4 : + break; // 可选 + case 4: ch = "四月"; - break; //可选 - case 5 : + break; // 可选 + case 5: ch = "五月"; - break; //可选 - case 6 : + break; // 可选 + case 6: ch = "六月"; - break; //可选 - case 7 : + break; // 可选 + case 7: ch = "七月"; - break; //可选 - case 8 : + break; // 可选 + case 8: ch = "八月"; - break; //可选 - case 9 : + break; // 可选 + case 9: ch = "九月"; - break; //可选 - case 10 : + break; // 可选 + case 10: ch = "十月"; - break; //可选 - case 11 : + break; // 可选 + case 11: ch = "十一月"; - break; //可选 - case 12 : + break; // 可选 + case 12: ch = "十二月"; - break; //可选 - default : ch = "";//可选 - //语句 + break; // 可选 + default: + ch = ""; // 可选 + // 语句 } return ch; } - } diff --git a/src/main/java/cn/hellohao/controller/AlbumController.java b/src/main/java/cn/hellohao/controller/AlbumController.java index 427da9c..3b3b000 100644 --- a/src/main/java/cn/hellohao/controller/AlbumController.java +++ b/src/main/java/cn/hellohao/controller/AlbumController.java @@ -97,7 +97,8 @@ public class AlbumController { } - @PostMapping("/admin/getAlbumListForKey") + //后台列表要修改时的查询表单 + @PostMapping("/admin/getAlbumListForKey") @ResponseBody public Msg getAlbumListForKey(@RequestParam(value = "data", defaultValue = "") String data){ Msg msg = new Msg(); @@ -213,6 +214,8 @@ public class AlbumController { String password = jsonObject.getString("password"); JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("albumlist")); if(null!=password){ +// String regex = "^[a-z0-9A-Z\u4e00-\u9fa5]+$"; +// return str.matches(regex); password = password.replace(" ", ""); if(password.replace(" ", "").equals("") || password.length()<3){ msg.setCode("110403"); diff --git a/src/main/java/cn/hellohao/controller/ClientAppController.java b/src/main/java/cn/hellohao/controller/ClientAppController.java index f2c1adf..2be294c 100644 --- a/src/main/java/cn/hellohao/controller/ClientAppController.java +++ b/src/main/java/cn/hellohao/controller/ClientAppController.java @@ -85,14 +85,30 @@ public class ClientAppController { return msg; } - @PostMapping("/imgUploading") - public Msg imgUploading(@RequestParam(required = true, value = "data") String data, HttpServletRequest request) { + @PostMapping("/imgUpload") + public Msg imgUpload(HttpServletRequest request, @RequestParam(required = true, value = "file") MultipartFile file, + @RequestParam(required = true, value = "days") String days) { + Msg msg = new Msg(); + try{ + if (null != file) { + msg = uploadServicel.uploadForLoc(request,file,Integer.valueOf(days),null); + }else{ + msg.setCode("500"); + } + }catch (Exception e){ + e.printStackTrace(); + msg.setCode("500"); + } + return msg; + } + + @PostMapping("/imgUploadForCopy") + public Msg imgUploadForCopy(@RequestParam(required = true, value = "data") String data, HttpServletRequest request) { Msg msg = new Msg(); try{ JSONObject jsonObj = JSONObject.parseObject(data); String imgstr = jsonObj.getString("imgstr"); Integer days = jsonObj.getInteger("days"); -// String imgclass = jsonObj.getString("imgclass"); if (null != imgstr && !imgstr.isEmpty()) { MultipartFile multipartFile = Base64ToMultipartFile.base64Convert(imgstr); msg = uploadServicel.uploadForLoc(request, multipartFile, days, null); diff --git a/src/main/java/cn/hellohao/controller/ClientController.java b/src/main/java/cn/hellohao/controller/ClientController.java index 32ec742..da6e6ac 100644 --- a/src/main/java/cn/hellohao/controller/ClientController.java +++ b/src/main/java/cn/hellohao/controller/ClientController.java @@ -22,6 +22,7 @@ public class ClientController { @Autowired private ClientService clientService; + @PostMapping(value = "/uploadbymail") @ResponseBody public Msg uploadbymail(HttpServletRequest request, @RequestParam("file") MultipartFile file, String mail, String pass) { diff --git a/src/main/java/cn/hellohao/controller/ExceptionHandling.java b/src/main/java/cn/hellohao/controller/ExceptionHandling.java index 3b5dc15..eec709f 100644 --- a/src/main/java/cn/hellohao/controller/ExceptionHandling.java +++ b/src/main/java/cn/hellohao/controller/ExceptionHandling.java @@ -24,6 +24,7 @@ public class ExceptionHandling { ModelAndView modelAndView = new ModelAndView("index"); Print.Normal("异常拦截成功:"+ ssie.getMessage()); modelAndView.addObject("error",ssie.getMessage()); + //返回错误信息,并显示给用户 return modelAndView; } diff --git a/src/main/java/cn/hellohao/controller/ImageReviewController.java b/src/main/java/cn/hellohao/controller/ImageReviewController.java index ad79c86..e5d4daa 100644 --- a/src/main/java/cn/hellohao/controller/ImageReviewController.java +++ b/src/main/java/cn/hellohao/controller/ImageReviewController.java @@ -20,7 +20,7 @@ public class ImageReviewController { private ImgreviewService imgreviewService; - @PostMapping("/updateimgReviewConfig") + @PostMapping("/updateimgReviewConfig") //new @ResponseBody public Msg updateimgReviewConfig(@RequestParam(value = "data", defaultValue = "") String data ) { final Msg msg = new Msg(); diff --git a/src/main/java/cn/hellohao/controller/IndexController.java b/src/main/java/cn/hellohao/controller/IndexController.java index 241bde8..fbc21eb 100644 --- a/src/main/java/cn/hellohao/controller/IndexController.java +++ b/src/main/java/cn/hellohao/controller/IndexController.java @@ -8,8 +8,6 @@ import cn.hellohao.service.impl.UploadServicel; import cn.hellohao.service.impl.deleImages; import cn.hellohao.utils.GetIPS; import cn.hellohao.utils.MyVersion; -import cn.hellohao.utils.verifyCode.IVerifyCodeGen; -import cn.hellohao.utils.verifyCode.SimpleCharVerifyCodeGenImpl; import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.ShearCaptcha; import cn.hutool.captcha.generator.MathGenerator; @@ -22,86 +20,79 @@ 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.*; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; import java.util.List; -import java.util.Timer; -import java.util.TimerTask; import java.util.UUID; @Controller public class IndexController { - @Autowired - private ImgService imgService; - @Autowired - private SysConfigService sysConfigService; - @Autowired - private ConfigService configService; - @Autowired - private UploadConfigService uploadConfigService; - @Autowired - private UploadServicel uploadServicel; - @Autowired - private deleImages deleimages; - @Autowired - IRedisService iRedisService; - @Autowired - AlbumServiceImpl albumService; - @Autowired - AppClientService appClientService; + @Autowired private ImgService imgService; + @Autowired private SysConfigService sysConfigService; + @Autowired private ConfigService configService; + @Autowired private UploadConfigService uploadConfigService; + @Autowired private UploadServicel uploadServicel; + @Autowired private deleImages deleimages; + @Autowired private IRedisService iRedisService; + @Autowired private AlbumServiceImpl albumService; + @Autowired private AppClientService appClientService; @RequestMapping(value = "/") public String Welcome(Model model, HttpServletRequest httpServletRequest) { - model.addAttribute("name","服务端程序"); - model.addAttribute("version","20221027"); - model.addAttribute("ip",GetIPS.getIpAddr(httpServletRequest)); - model.addAttribute("links","tbed.hellohao.cn"); + model.addAttribute("name", "服务端程序"); + model.addAttribute("version", "20221027"); + model.addAttribute("ip", GetIPS.getIpAddr(httpServletRequest)); + model.addAttribute("links", "tbed.hellohao.cn"); return "welcome"; } @RequestMapping(value = "/webInfo") @ResponseBody public Msg webInfo() { - final Msg msg = new Msg(); + Msg msg = new Msg(); Config config = configService.getSourceype(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); SysConfig sysConfig = sysConfigService.getstate(); JSONObject jsonObject = new JSONObject(); AppClient appClient = appClientService.getAppClientData("app"); - jsonObject.put("webname",config.getWebname()); - jsonObject.put("websubtitle",config.getWebsubtitle()); - jsonObject.put("keywords",config.getWebkeywords()); - jsonObject.put("description",config.getWebms()); - jsonObject.put("explain",config.getExplain()); - jsonObject.put("favicon",config.getWebfavicons()); - jsonObject.put("baidu",config.getBaidu()); - jsonObject.put("links",config.getLinks()); - jsonObject.put("aboutinfo",config.getAboutinfo()); - jsonObject.put("logo",config.getLogo()); - jsonObject.put("api",updateConfig.getApi()); - jsonObject.put("register",sysConfig.getRegister()); - jsonObject.put("isuse",appClient.getIsuse()); - jsonObject.put("clientname",appClient.getAppname()); - jsonObject.put("clientlogo",appClient.getApplogo()); - jsonObject.put("appupdate",appClient.getAppupdate()); + 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("register", sysConfig.getRegister()); + jsonObject.put("isuse", appClient.getIsuse()); + jsonObject.put("clientname", appClient.getAppname()); + jsonObject.put("clientlogo", appClient.getApplogo()); + jsonObject.put("appupdate", appClient.getAppupdate()); msg.setData(jsonObject); return msg; } - @PostMapping(value = {"/upload","/client/upload"}) + @PostMapping(value = {"/upload", "/client/upload"}) @ResponseBody - public Msg upimg(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile multipartFile,Integer day) { - return uploadServicel.uploadForLoc(request,multipartFile,day,null); + public Msg upimg( + HttpServletRequest request, + @RequestParam(value = "file", required = false) MultipartFile multipartFile, + Integer day) { + return uploadServicel.uploadForLoc(request, multipartFile, day, null); } - @PostMapping(value = {"/uploadForUrl","/client/uploadForUrl"}) + @PostMapping(value = {"/uploadForUrl", "/client/uploadForUrl"}) @ResponseBody - public Msg upurlimg(HttpServletRequest request,@RequestParam(value = "data", defaultValue = "") String data) { + public Msg upurlimg( + HttpServletRequest request, @RequestParam(value = "data", defaultValue = "") String data) { JSONObject jsonObj = JSONObject.parseObject(data); Integer setday = jsonObj.getInteger("day"); String imgUrl = jsonObj.getString("imgUrl"); @@ -111,9 +102,9 @@ public class IndexController { User user = (User) subject.getPrincipal(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); int syscounts = 0; - if(null==user){ + if (null == user) { syscounts = updateConfig.getImgcounttourists(); - }else{ + } else { syscounts = updateConfig.getImgcountuser(); } Msg retMsg = new Msg(); @@ -122,22 +113,22 @@ public class IndexController { int errcounts = 0; int excess = 0; for (int i = 0; i < URLArr.length; i++) { - int temp = i+1; - if(syscounts>=temp){ + int temp = i + 1; + if (syscounts >= temp) { Msg msg = uploadServicel.uploadForLoc(request, null, setday, URLArr[i]); - if(!msg.getCode().equals("200")){ + if (!msg.getCode().equals("200")) { errcounts++; - }else{ + } else { retArray.add(msg); } - }else{ + } else { excess++; } } - jsonObject.put("counts",URLArr.length); - jsonObject.put("errcounts",errcounts); - jsonObject.put("excess",excess); - jsonObject.put("urls",retArray); + jsonObject.put("counts", URLArr.length); + jsonObject.put("errcounts", errcounts); + jsonObject.put("excess", excess); + jsonObject.put("urls", retArray); retMsg.setData(jsonObject); return retMsg; } @@ -151,19 +142,19 @@ public class IndexController { 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()); - jsonObject.put("uploadSwitch",updateConfig.getUserclose()); - jsonObject.put("uploadInfo","系统暂时关闭了用户上传功能"); + 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()); + jsonObject.put("uploadSwitch", updateConfig.getUserclose()); + jsonObject.put("uploadInfo", "系统暂时关闭了用户上传功能"); } - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } msg.setData(jsonObject); @@ -175,19 +166,21 @@ public class IndexController { public Msg checkStatus(HttpServletRequest request) { Msg msg = new Msg(); String token = request.getHeader("Authorization"); - if(token != null) { + if (token != null) { JSONObject tokenJson = JWTUtil.checkToken(token); - if(tokenJson.getBoolean("check")){ + if (tokenJson.getBoolean("check")) { Subject subject = SecurityUtils.getSubject(); - UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(tokenJson.getString("email"),tokenJson.getString("password")); + UsernamePasswordToken tokenOBJ = + new UsernamePasswordToken( + tokenJson.getString("email"), tokenJson.getString("password")); tokenOBJ.setRememberMe(true); 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"); - jsonObject.put("userName",u.getUsername()); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("RoleLevel", u.getLevel() == 2 ? "admin" : "user"); + jsonObject.put("userName", u.getUsername()); msg.setCode("200"); msg.setData(jsonObject); } catch (Exception e) { @@ -196,18 +189,17 @@ public class IndexController { System.err.println("登录失效,请重新登录"); e.printStackTrace(); } - }else{ + } else { msg.setCode("40041"); msg.setInfo("登录失效,请重新登录"); } - }else{ + } else { msg.setCode("40040"); msg.setInfo("当前未登录,请先登录"); } return msg; } - @PostMapping("/verifyCode") @ResponseBody public Msg verifyCode() { @@ -217,10 +209,10 @@ public class IndexController { captcha.setGenerator(new MathGenerator(1)); String code = getVerifyCodeOperator(captcha.getCode()); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); - iRedisService.setValue("verifyCode_"+uid,code); + iRedisService.setValue("verifyCode_" + uid, code); JSONObject jsonObject = new JSONObject(); - jsonObject.put("codeKey",uid); - jsonObject.put("codeImg",captcha.getImageBase64()); + jsonObject.put("codeKey", uid); + jsonObject.put("codeImg", captcha.getImageBase64()); msg.setData(jsonObject); return msg; } catch (Exception e) { @@ -239,14 +231,15 @@ public class IndexController { captcha.setGenerator(new MathGenerator(1)); String code = getVerifyCodeOperator(captcha.getCode()); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); - iRedisService.setValue("verifyCodeForRegister_"+uid,code); + iRedisService.setValue("verifyCodeForRegister_" + uid, code); JSONObject jsonObject = new JSONObject(); - jsonObject.put("codeKey",uid); - jsonObject.put("codeImg",captcha.getImageBase64()); + jsonObject.put("codeKey", uid); + jsonObject.put("codeImg", captcha.getImageBase64()); msg.setData(jsonObject); return msg; } catch (Exception e) { - e.printStackTrace();msg.setCode("500"); + e.printStackTrace(); + msg.setCode("500"); return msg; } } @@ -260,10 +253,10 @@ public class IndexController { captcha.setGenerator(new MathGenerator(1)); String code = getVerifyCodeOperator(captcha.getCode()); String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); - iRedisService.setValue("verifyCodeForRetrieve_"+uid,code); + iRedisService.setValue("verifyCodeForRetrieve_" + uid, code); JSONObject jsonObject = new JSONObject(); - jsonObject.put("codeKey",uid); - jsonObject.put("codeImg",captcha.getImageBase64()); + jsonObject.put("codeKey", uid); + jsonObject.put("codeImg", captcha.getImageBase64()); msg.setData(jsonObject); return msg; } catch (Exception e) { @@ -273,11 +266,11 @@ public class IndexController { } } - public static String getVerifyCodeOperator(String str){ - int a = Integer.valueOf(str.substring(0,1)); - String yxf = str.substring(1,2); - int b = Integer.valueOf(str.substring(2,3)); - switch(yxf) { + public static String getVerifyCodeOperator(String str) { + int a = Integer.valueOf(str.substring(0, 1)); + String yxf = str.substring(1, 2); + int b = Integer.valueOf(str.substring(2, 3)); + switch (yxf) { case "*": return Integer.toString(a * b); case "+": @@ -288,35 +281,34 @@ public class IndexController { case "-": return Integer.toString(a - b); } - } - @PostMapping({"/deleImagesByUid","/client/deleImagesByUid"}) + @PostMapping({"/deleImagesByUid", "/client/deleImagesByUid"}) @ResponseBody public Msg deleImagesByUid(@RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); JSONObject jsonObj = JSONObject.parseObject(data); String imguid = jsonObj.getString("imguid"); Images image = imgService.selectImgUrlByImgUID(imguid); - if(null==image){ + if (null == image) { msg.setInfo("图像已不存在,删除成功"); return msg; } Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); - if(null!=user){ - if(!user.getId().equals(image.getUserid())){ + if (null != user) { + if (!user.getId().equals(image.getUserid())) { msg.setInfo("删除失败,该图片不允许你执行操作"); msg.setCode("100403"); return msg; } } - msg = deleimages.dele(null,image.getId()); - List Delids = (List)msg.getData(); - if(!Delids.contains(image.getId())){ + msg = deleimages.dele(null, image.getId()); + List Delids = (List) msg.getData(); + if (!Delids.contains(image.getId())) { msg.setCode("500"); msg.setInfo("图像删除失败"); - }else{ + } else { msg.setCode("200"); msg.setInfo("图像已成功删除"); } @@ -332,26 +324,25 @@ public class IndexController { JSONObject jsonObj = JSONObject.parseObject(data); String appv = jsonObj.getString("version"); AppClient app = appClientService.getAppClientData("app"); - if(!StringUtils.isBlank(app.getAppupdate())){ - String version = app.getAppupdate().replaceAll("\\.",""); - if(MyVersion.compareVersion(app.getAppupdate(),appv)==1){ + if (!StringUtils.isBlank(app.getAppupdate())) { + String version = app.getAppupdate().replaceAll("\\.", ""); + if (MyVersion.compareVersion(app.getAppupdate(), appv) == 1) { JSONObject jsonObject = new JSONObject(); - jsonObject.put("winpackurl",app.getWinpackurl()); - jsonObject.put("macpackurl",app.getMacpackurl()); + jsonObject.put("winpackurl", app.getWinpackurl()); + jsonObject.put("macpackurl", app.getMacpackurl()); msg.setCode("200"); msg.setData(jsonObject); } } - }catch (Exception e){ + } catch (Exception e) { msg.setCode("000"); } return msg; } - @RequestMapping("/authError") @ResponseBody - public Msg authError(HttpServletRequest request){ + public Msg authError(HttpServletRequest request) { Msg msg = new Msg(); msg.setCode("4031"); msg.setInfo("You don't have authority"); @@ -360,13 +351,10 @@ public class IndexController { @RequestMapping("/jurisError") @ResponseBody - public Msg jurisError(HttpServletRequest request){ + public Msg jurisError(HttpServletRequest request) { Msg msg = new Msg(); msg.setCode("4031"); msg.setInfo("Authentication request failed"); return msg; } - - - } diff --git a/src/main/java/cn/hellohao/controller/MainsiteErrorController.java b/src/main/java/cn/hellohao/controller/MainsiteErrorController.java deleted file mode 100644 index 2f5b942..0000000 --- a/src/main/java/cn/hellohao/controller/MainsiteErrorController.java +++ /dev/null @@ -1,46 +0,0 @@ -package cn.hellohao.controller; - -import cn.hellohao.pojo.Msg; -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.servlet.http.HttpServletRequest; - -/** - * 错误页面拦截 - * */ - -@Controller -class MainsiteErrorController implements ErrorController { - - @RequestMapping("/error") - @ResponseBody - public Msg handleError(HttpServletRequest request){ - Msg msg = new Msg(); - msg.setExceptions("Error intercepted by Hellohao"); - //获取statusCode:401,404,500 - Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); - if(statusCode == 401){ - msg.setCode("401"); - msg.setInfo("Request error for 401"); - return msg; - }else if(statusCode == 404){ - msg.setCode("404"); - msg.setInfo("Request not found 404"); - return msg; - }else if(statusCode == 403){ - msg.setCode("403"); - msg.setInfo("Request error for 403"); - return msg; - }else{ - msg.setCode("500"); - msg.setInfo("System internal error"); - return msg; - } - - } - - -} \ No newline at end of file diff --git a/src/main/java/cn/hellohao/controller/UserController.java b/src/main/java/cn/hellohao/controller/UserController.java index f83430c..6856f0f 100644 --- a/src/main/java/cn/hellohao/controller/UserController.java +++ b/src/main/java/cn/hellohao/controller/UserController.java @@ -45,14 +45,15 @@ public class UserController { @PostMapping("/register") @ResponseBody - public Msg Register(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) { + public Msg Register(HttpSession httpSession, @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 verifyCodeForRegister = jsonObj.getString("verifyCode"); - Object redis_verifyCodeForRegister = iRedisService.getValue("verifyCodeForRegister_"+httpServletRequest.getHeader("verifyCodeForRegister")); if(!SetText.checkEmail(email)){ + ShearCaptcha redis_verifyCodeForRegister = (ShearCaptcha) httpSession.getAttribute("_hellohao_verifyCodeForRegister");//iRedisService.getValue(userIP+"_verifyCodeForRegister"); + if(!SetText.checkEmail(email)){ msg.setCode("110403"); msg.setInfo("邮箱格式不正确"); return msg; @@ -72,7 +73,7 @@ public class UserController { msg.setInfo("验证码不能为空。"); return msg; } - if((redis_verifyCodeForRegister.toString().toLowerCase()).compareTo((verifyCodeForRegister.toLowerCase()))==0){ + if(redis_verifyCodeForRegister.verify(verifyCodeForRegister.toLowerCase())){ User user = new User(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); EmailConfig emailConfig = emailConfigService.getemail(); @@ -96,7 +97,7 @@ public class UserController { } String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 - String birthder = df.format(new Date()); + String birthder = df.format(new Date());// new Date()为获取当前系统时间 user.setLevel(1); user.setUid(uid); user.setBirthder(birthder); @@ -123,20 +124,20 @@ public class UserController { userService.register(user); }else{ msg.setCode("110408"); - msg.setInfo("验证码不正确"); + msg.setInfo("验证码不正确");//失效也要处理。 } return msg; } - @PostMapping("/login") + @PostMapping("/login")//new @ResponseBody - public Msg login(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) { + public Msg login(HttpServletRequest request,HttpSession httpSession,@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"); - Object redis_VerifyCode = iRedisService.getValue("verifyCode_"+httpServletRequest.getHeader("verifyCode")); + ShearCaptcha redis_VerifyCode = (ShearCaptcha)httpSession.getAttribute("_hellohao_verifyCode"); if(null==redis_VerifyCode){ msg.setCode("4035"); msg.setInfo("验证码已失效,请重新弄获取。"); @@ -146,7 +147,7 @@ public class UserController { msg.setInfo("验证码不能为空。"); return msg; } - if((redis_VerifyCode.toString().toLowerCase()).compareTo((verifyCode.toLowerCase()))==0){ + if(redis_VerifyCode.verify(verifyCode.toLowerCase())){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(email,password); tokenOBJ.setRememberMe(true); @@ -175,6 +176,7 @@ public class UserController { msg.setData(jsonObject); return msg; } catch (UnknownAccountException e) { + //此异常说明用户名不存在 msg.setCode("4000"); msg.setInfo("登录邮箱不存在"); System.err.println("邮箱不存在"); @@ -223,7 +225,7 @@ public class UserController { } } - @PostMapping(value = "/logout") + @PostMapping(value = "/logout")//new @ResponseBody public Msg exit(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { Msg msg = new Msg(); @@ -234,15 +236,15 @@ public class UserController { return msg; } - @PostMapping("/retrievePass") + @PostMapping("/retrievePass") //new @ResponseBody - public Msg retrievePass(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) { + public Msg retrievePass(HttpServletRequest request,HttpSession httpSession, @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"); - Object redis_verifyCodeForEmailRetrieve =iRedisService.getValue("verifyCodeForRetrieve_"+httpServletRequest.getHeader("verifyCodeForRetrieve")); + ShearCaptcha redis_verifyCodeForEmailRetrieve =(ShearCaptcha) httpSession.getAttribute("_hellohao_verifyCodeForEmailRetrieve");// iRedisService.getValue(userIP+"_verifyCodeForEmailRetrieve"); EmailConfig emailConfig = emailConfigService.getemail(); if(null==redis_verifyCodeForEmailRetrieve){ msg.setCode("4035"); @@ -253,11 +255,12 @@ public class UserController { msg.setInfo("验证码不能为空。"); return msg; } - if((redis_verifyCodeForEmailRetrieve.toString().toLowerCase()).compareTo((retrieveCode.toLowerCase()))!=0){ + if(!redis_verifyCodeForEmailRetrieve.verify(retrieveCode.toLowerCase())){ msg.setCode("40034"); msg.setInfo("验证码不正确"); return msg; } + Integer ret = userService.countmail(email); if(ret>0){ if(emailConfig.getUsing()==1){ @@ -293,7 +296,7 @@ public class UserController { return msg; } - @RequestMapping(value = "/retrieve", method = RequestMethod.GET) + @RequestMapping(value = "/retrieve", method = RequestMethod.GET) //new public String retrieve(Model model, String activation,String cip) { Integer ret = 0; try { diff --git a/src/main/java/cn/hellohao/service/IRedisService.java b/src/main/java/cn/hellohao/service/IRedisService.java index 2e9a374..fba7113 100644 --- a/src/main/java/cn/hellohao/service/IRedisService.java +++ b/src/main/java/cn/hellohao/service/IRedisService.java @@ -4,14 +4,16 @@ 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 + // 加入元素 + void setValue(String key, Map value); + // 加入元素 + void setValue(String key, String value); + // 加入元素 + void setTimeValue(String key, Object value,Long time); + // 获取元素 + Object getMapValue(String key); + // 获取元素 + Object getValue(String key); + // 删除某个值 + Boolean removeValue(String key); +} diff --git a/src/main/java/cn/hellohao/service/impl/AlbumServiceImpl.java b/src/main/java/cn/hellohao/service/impl/AlbumServiceImpl.java index 8b09e16..0b1965b 100644 --- a/src/main/java/cn/hellohao/service/impl/AlbumServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/AlbumServiceImpl.java @@ -8,16 +8,13 @@ import cn.hellohao.exception.CodeException; import cn.hellohao.pojo.Album; import cn.hellohao.pojo.Images; import cn.hellohao.pojo.ImgAndAlbum; -import cn.hellohao.pojo.Msg; import cn.hellohao.service.AlbumService; import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; -import java.util.UUID; /** * @author Hellohao @@ -26,92 +23,86 @@ import java.util.UUID; */ @Service public class AlbumServiceImpl implements AlbumService { - @Autowired - AlbumMapper albumMapper; - @Autowired - ImgAndAlbumMapper andAlbumMapper; - @Autowired - ConfigMapper configMapper; - @Autowired - ImgMapper imgMapper; + @Autowired AlbumMapper albumMapper; + @Autowired ImgAndAlbumMapper andAlbumMapper; + @Autowired ConfigMapper configMapper; + @Autowired ImgMapper imgMapper; - @Override - public JSONArray getAlbumList(JSONArray array) { - JSONArray jsonArray = new JSONArray(); - for (int i = 0; i < array.size(); i++) { - Images images = new Images(); - images.setImguid(array.getString(i)); - jsonArray.add(imgMapper.selectimg(images).get(0)); - } - return jsonArray; + @Override + public JSONArray getAlbumList(JSONArray array) { + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < array.size(); i++) { + Images images = new Images(); + images.setImguid(array.getString(i)); + jsonArray.add(imgMapper.selectimg(images).get(0)); } + return jsonArray; + } - @Override - public Album selectAlbum(Album album) { - return albumMapper.selectAlbum(album); + @Override + public Album selectAlbum(Album album) { + return albumMapper.selectAlbum(album); + } + + @Override + public Integer addAlbum(Album album) { + return albumMapper.addAlbum(album); + } + + @Transactional + public Integer addAlbumForImgAndAlbumMapper(ImgAndAlbum imgAndAlbum) { + Integer tem = 0; + Integer r2 = andAlbumMapper.addImgAndAlbum(imgAndAlbum); + if (r2 > 0) { + tem = 1; + } else { + throw new CodeException("插入画廊数据失败,回滚"); } + return tem; + } - @Override - public Integer addAlbum(Album album) { - return albumMapper.addAlbum(album); + @Override + public Integer deleteAlbum(String albumkey) { + return albumMapper.deleteAlbum(albumkey); + } + + @Override + public List selectAlbumURLList(Album album) { + return albumMapper.selectAlbumURLList(album); + } + + @Override + public Integer selectAlbumCount(Integer userid) { + return albumMapper.selectAlbumCount(userid); + } + + @Override + public Integer updateAlbum(Album album) { + return albumMapper.updateAlbum(album); + } + + @Transactional + public Integer delete(String albumkey) { + Integer ret1 = albumMapper.deleteAlbum(albumkey); + if (ret1 > 0) { + ret1 = andAlbumMapper.deleteImgAndAlbumForKey(albumkey); + } else { + throw new CodeException("删除画廊失败。"); } + return ret1; + } - @Transactional - public Integer addAlbumForImgAndAlbumMapper(ImgAndAlbum imgAndAlbum) { - Integer tem = 0; - Integer r2 = andAlbumMapper.addImgAndAlbum(imgAndAlbum); - if(r2>0){ - tem = 1; - }else{ - throw new CodeException("插入画廊数据失败,回滚"); - } - return tem; + @Transactional + public Integer deleteAll(String[] albumkeyArr) { + Integer ret1 = 0; + for (String s : albumkeyArr) { + ret1 = albumMapper.deleteAlbum(s); + if (ret1 > 0) { + ret1 = andAlbumMapper.deleteImgAndAlbumForKey(s); + } else { + throw new CodeException("删除画廊失败。"); + } } - - @Override - public Integer deleteAlbum(String albumkey) { - return albumMapper.deleteAlbum(albumkey); - } - - @Override - public List selectAlbumURLList(Album album) { - return albumMapper.selectAlbumURLList(album); - } - - @Override - public Integer selectAlbumCount(Integer userid) { - return albumMapper.selectAlbumCount(userid); - } - - @Override - public Integer updateAlbum(Album album) { - return albumMapper.updateAlbum(album); - } - - @Transactional - public Integer delete(String albumkey) { - Integer ret1 = albumMapper.deleteAlbum(albumkey); - if(ret1>0){ - ret1 = andAlbumMapper.deleteImgAndAlbumForKey(albumkey); - }else{ - throw new CodeException("删除画廊失败。"); - } - return ret1; - } - - @Transactional - public Integer deleteAll(String[] albumkeyArr) { - Integer ret1 = 0 ; - for (String s : albumkeyArr) { - ret1 = albumMapper.deleteAlbum(s); - if(ret1>0){ - ret1 = andAlbumMapper.deleteImgAndAlbumForKey(s); - }else{ - throw new CodeException("删除画廊失败。"); - } - } - return ret1; - } - - + return ret1; + } } diff --git a/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java b/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java index 9dc72ba..cf09bb6 100644 --- a/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/RedisServiceImpl.java @@ -12,42 +12,44 @@ import java.util.concurrent.TimeUnit; @Service public class RedisServiceImpl implements IRedisService { - @Autowired - private StringRedisTemplate stringRedisTemplate; - @Autowired - private RedisTemplate redisTemplate; + @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 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 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, String value) { - ValueOperations vo = redisTemplate.opsForValue(); - vo.set(key, value); - redisTemplate.expire(key, 3, TimeUnit.MINUTES); // 这里指的是1小时后失效 时HOURS 分 MINUTES - } + @Override + public void setTimeValue(String key, Object value, Long time) { + ValueOperations vo = redisTemplate.opsForValue(); + vo.set(key, value); + redisTemplate.expire(key, time, TimeUnit.HOURS); + } - @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); + } - @Override - public Object getMapValue(String key) { - ValueOperations vo = redisTemplate.opsForValue(); - return vo.get(key); - } -} \ No newline at end of file + @Override + public Boolean removeValue(String key) { + return redisTemplate.delete(key); + } +} diff --git a/src/main/java/cn/hellohao/service/impl/UploadServicel.java b/src/main/java/cn/hellohao/service/impl/UploadServicel.java index 00d73f8..8805deb 100644 --- a/src/main/java/cn/hellohao/service/impl/UploadServicel.java +++ b/src/main/java/cn/hellohao/service/impl/UploadServicel.java @@ -52,7 +52,6 @@ public class UploadServicel { MultipartFile multipartFile, Integer setday, String imgUrl) { Msg msg = new Msg(); try{ - String imageFileName = "未命名图像"; JSONObject jsonObject = new JSONObject(); UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig(); String userip = GetIPS.getIpAddr(request); @@ -66,7 +65,6 @@ public class UploadServicel { FileInputStream fis = null; File file =null; if(imgUrl==null){ - imageFileName = multipartFile.getOriginalFilename(); file = SetFiles.changeFile_new(multipartFile); }else{ Msg imgData = uploadForURL(request, imgUrl); @@ -174,7 +172,6 @@ public class UploadServicel { img.setMd5key(md5key); img.setImguid(imguid); img.setFormat(fileMiME.getData().toString()); - img.setIdname(imageFileName); userMapper.insertimg(img); long etime = System.currentTimeMillis(); Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms"); diff --git a/src/main/java/cn/hellohao/service/impl/deleImages.java b/src/main/java/cn/hellohao/service/impl/deleImages.java index c395c48..549f9c0 100644 --- a/src/main/java/cn/hellohao/service/impl/deleImages.java +++ b/src/main/java/cn/hellohao/service/impl/deleImages.java @@ -3,104 +3,105 @@ package cn.hellohao.service.impl; import cn.hellohao.pojo.Images; import cn.hellohao.pojo.Keys; import cn.hellohao.pojo.Msg; +import cn.hellohao.service.IRedisService; import cn.hellohao.service.ImgAndAlbumService; import cn.hellohao.service.ImgService; import cn.hellohao.service.ImgTempService; import cn.hellohao.utils.LocUpdateImg; import cn.hellohao.utils.progress.MyProgress; +import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.servlet.http.HttpSession; + import java.util.ArrayList; import java.util.List; @Service public class deleImages { + @Autowired private NOSImageupload nosImageupload; + @Autowired private OSSImageupload ossImageupload; + @Autowired private COSImageupload cosImageupload; + @Autowired private KODOImageupload kodoImageupload; + @Autowired private USSImageupload ussImageupload; + @Autowired private UFileImageupload uFileImageupload; + @Autowired private FTPImageupload ftpImageupload; + @Autowired private ImgAndAlbumService imgAndAlbumService; + @Autowired private ImgTempService imgTempService; + @Autowired private ImgService imgService; + @Autowired private KeysServiceImpl keysService; + @Autowired private IRedisService iRedisService; - @Autowired - private NOSImageupload nosImageupload; - @Autowired - private OSSImageupload ossImageupload; - @Autowired - private COSImageupload cosImageupload; - @Autowired - private KODOImageupload kodoImageupload; - @Autowired - private USSImageupload ussImageupload; - @Autowired - private UFileImageupload uFileImageupload; - @Autowired - private FTPImageupload ftpImageupload; - @Autowired - private ImgAndAlbumService imgAndAlbumService; - @Autowired - private ImgTempService imgTempService; - @Autowired - private ImgService imgService; - @Autowired - private KeysServiceImpl keysService; - - - public Msg dele(HttpSession httpSession,Integer... imgIds) { - Msg msg = new Msg(); - MyProgress myProgress = new MyProgress(); - myProgress.InitializeDelImg(); - List ids = new ArrayList<>(); - int successCount = 0; - List errorIds = new ArrayList<>(); - for (Integer id : imgIds) { - //删除图片 - boolean isDele = false; - try { - Images image = imgService.selectByPrimaryKey(id); - Keys key = keysService.selectKeys(image.getSource()); - if (key.getStorageType() == 1) { - isDele = nosImageupload.delNOS(key.getId(), image); - } else if (key.getStorageType() == 2) { - isDele = ossImageupload.delOSS(key.getId(), image); - } else if (key.getStorageType() == 3) { - isDele = ussImageupload.delUSS(key.getId(), image); - } else if (key.getStorageType() == 4) { - isDele = kodoImageupload.delKODO(key.getId(), image); - } else if (key.getStorageType() == 5) { - isDele = LocUpdateImg.deleteLOCImg(image); - } else if (key.getStorageType() == 6) { - isDele = cosImageupload.delCOS(key.getId(), image); - } else if (key.getStorageType() == 7) { - isDele = ftpImageupload.delFTP(key.getId(), image); - } else if (key.getStorageType() == 8) { - isDele = uFileImageupload.delUFile(key.getId(), image); - } else { - System.err.println("未获取到对象存储参数,删除失败。"); - } - if(isDele){ - try { - imgAndAlbumService.deleteImgAndAlbum(image.getImgurl()); - imgTempService.delImgAndExp(image.getImguid()); - imgService.deleimg(image.getId()); - ids.add(image.getId()); - successCount++; - System.out.println("删除成功加一个"+image.getId()); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(image.getImgname()+":图片数据库记录时发生错误"); - errorIds.add(image.getImgurl()); - } - } - myProgress.setDelSuccessCount(successCount); - myProgress.setDelSuccessImgList(ids); - myProgress.setDelErrorImgListt(errorIds); - if(null !=httpSession){ - httpSession.setAttribute("myProgressForDel",myProgress); - } - } catch (Exception e) { - System.err.println("删除的时候发生了一些异常"); - e.printStackTrace(); - } + public Msg dele(String uuid, Integer... imgIds) { + Msg msg = new Msg(); + MyProgress myProgress = new MyProgress(); + myProgress.InitializeDelImg(); + List ids = new ArrayList<>(); + int successCount = 0; + List errorIds = new ArrayList<>(); + for (int i = 0; i < imgIds.length; i++) { + // 删除图片 + boolean isDele = false; + try { + Images image = imgService.selectByPrimaryKey(imgIds[i]); + Keys key = keysService.selectKeys(image.getSource()); + if (key.getStorageType() == 1) { + isDele = nosImageupload.delNOS(key.getId(), image); + } else if (key.getStorageType() == 2) { + isDele = ossImageupload.delOSS(key.getId(), image); + } else if (key.getStorageType() == 3) { + isDele = ussImageupload.delUSS(key.getId(), image); + } else if (key.getStorageType() == 4) { + isDele = kodoImageupload.delKODO(key.getId(), image); + } else if (key.getStorageType() == 5) { + isDele = LocUpdateImg.deleteLOCImg(image); + } else if (key.getStorageType() == 6) { + isDele = cosImageupload.delCOS(key.getId(), image); + } else if (key.getStorageType() == 7) { + isDele = ftpImageupload.delFTP(key.getId(), image); + } else if (key.getStorageType() == 8) { + isDele = uFileImageupload.delUFile(key.getId(), image); + } else { + System.err.println("未获取到对象存储参数,删除失败。"); } - myProgress.setDelOCT(true); - msg.setData(ids); - return msg; + if (isDele) { + try { + imgAndAlbumService.deleteImgAndAlbum(image.getImgurl()); + imgTempService.delImgAndExp(image.getImguid()); + imgService.deleimg(image.getId()); + ids.add(image.getId()); + successCount++; + System.out.println("删除成功加一个" + image.getId()); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(image.getImgname() + ":图片数据库记录时发生错误"); + errorIds.add(image.getImgurl()); + } + } + myProgress.setDelSuccessCount(successCount); + myProgress.setDelSuccessImgList(ids); + myProgress.setDelErrorImgListt(errorIds); + if (imgIds.length == (i + 1)) { + myProgress.setDelOCT(1); + } else { + myProgress.setDelOCT(0); + } + iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L); + // if (null != httpSession) { + // httpSession.setAttribute("myProgressForDel", myProgress); + // } + } catch (Exception e) { + System.err.println("删除的时候发生了一些异常"); + e.printStackTrace(); + } } + msg.setData(ids); + return msg; + } + + public static void main(String[] args) { + MyProgress myProgress = new MyProgress(); + myProgress.InitializeDelImg(); + System.out.println(JSONObject.toJSONString(myProgress)); + } } diff --git a/src/main/java/cn/hellohao/utils/FirstRun.java b/src/main/java/cn/hellohao/utils/FirstRun.java index fc3ed84..d66afe0 100644 --- a/src/main/java/cn/hellohao/utils/FirstRun.java +++ b/src/main/java/cn/hellohao/utils/FirstRun.java @@ -32,13 +32,6 @@ public class FirstRun implements InitializingBean { RunSqlScript.USERNAME = jdbcusername; RunSqlScript.PASSWORD = jdbcpass; RunSqlScript.DBURL = jdbcurl; - - Integer dataBaseName = RunSqlScript.RunSelectCount("SELECT count(*) FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = 'tbed'"); - if(dataBaseName<1){ - Print.Normal("无法找到指定数据库,请先创建'tbed'数据库,并导入表结构后再试。"); - System.exit(1); - } - Print.Normal("正在校验数据库参数..."); RunSqlScript.RunInsert(dynamic); RunSqlScript.RunInsert(compressed); @@ -98,14 +91,15 @@ public class FirstRun implements InitializingBean { RunSqlScript.RunInsert(instartAppclient); Print.Normal("Add table.appclient"); } - Integer ret7 = RunSqlScript.RunSelectCount(judgeTable+" 'imgdata' and column_name = 'idname'"); - if(ret7==0){ - RunSqlScript.RunInsert(sql11); - Print.Normal("Add imgdata.idname"); - } +// Integer ret6 = RunSqlScript.RunSelectCount(judgeTable+" 'imgdata' and column_name = 'idname'"); +// if(ret6==0){ +// RunSqlScript.RunInsert(sql11); +// Print.Normal("Add imgdata.idname"); +// } RunSqlScript.RunInsert("alter table `config` modify column `explain` text,modify column `links` text,modify column `notice` text,modify column `baidu` text"); + //RunSqlScript.RunInsert("alter table imgdata drop index index_md5key_url"); RunSqlScript.RunInsert(inddx_md5key); RunSqlScript.RunInsert("UPDATE `keys` SET `Endpoint` = '0' WHERE `id` = 8"); Print.Normal("Stage success"); @@ -113,6 +107,7 @@ public class FirstRun implements InitializingBean { clears(); } + //检查表是否存在,后边加'imgdata' and column_name = 'explains' 检查字段是否存在 private String isTableName = "SELECT count(table_name) FROM information_schema.TABLES WHERE TABLE_SCHEMA='tbed' and table_name ="; private String judgeTable = "select count(*) from information_schema.columns where TABLE_SCHEMA='tbed' and table_name = "; //创建blacklist 2019-11-29 @@ -122,14 +117,23 @@ public class FirstRun implements InitializingBean { private String sql3 ="CREATE TABLE `imgandalbum` (`imgname` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`albumkey` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic"; private String sql4 ="CREATE TABLE `album` (`albumkey` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`albumtitle` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`createdate` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic"; private String sql6 = "alter table imgdata add explains varchar(5000)"; + //添加album表字段userid private String sql7 = "alter table album add userid int(10)"; + //添加imgdata表字段md5key private String sql8 = "alter table imgdata add md5key varchar(5000)"; private String sql9 = "ALTER TABLE config ADD theme int(4) DEFAULT '1' COMMENT '主题' "; - private String sql11 = "alter table `imgdata` add idname varchar(255) DEFAULT '未命名图像' ;"; + // 图片标识名字段 + private String sql11 = "alter table `imgdata` add idname varchar(255) DEFAULT '未命名' ;"; + private String sql12 = "alter table tbed.user add `token` varchar(255)"; + //创建客户端程序相关表 private String createAppclient = "CREATE TABLE `appclient` (`id` varchar(10) NOT NULL,`isuse` varchar(10) NOT NULL,`winpackurl` varchar(255) NULL DEFAULT NULL,`macpackurl` varchar(255) NULL DEFAULT NULL,`appname` varchar(20) NULL,`applogo` varchar(255) NULL,`appupdate` varchar(10) NOT NULL) "; private String instartAppclient = "INSERT INTO `appclient` VALUES ('app', 'on', NULL, NULL, 'Hellohao图像托管', 'https://hellohao.nos-eastchina1.126.net/TbedClient/app.png', '1.0.1');"; + + private String inddx_md5key = "ALTER TABLE imgdata ADD INDEX index_md5key_url ( md5key,imgurl)"; + // create index yarn_app_result_i4 on yarn_app_result (flow_exec_id(100), another_column(50)); + private String dynamic = "alter table imgdata row_format=dynamic"; private String compressed = "alter table imgdata row_format=compressed"; diff --git a/src/main/java/cn/hellohao/utils/LocUpdateImg.java b/src/main/java/cn/hellohao/utils/LocUpdateImg.java index b4e899e..c99249c 100644 --- a/src/main/java/cn/hellohao/utils/LocUpdateImg.java +++ b/src/main/java/cn/hellohao/utils/LocUpdateImg.java @@ -4,15 +4,10 @@ import cn.hellohao.config.GlobalConstant; import cn.hellohao.pojo.Images; 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.*; -import java.util.Date; -import java.util.HashMap; import java.util.Map; -import java.util.UUID; public class LocUpdateImg { public static boolean deleteLOCImg(Images images){ @@ -20,7 +15,11 @@ public class LocUpdateImg { try { String filePath = GlobalConstant.LOCPATH + File.separator+images.getImgname(); File file = new File(filePath); - isDele = file.delete(); + if(file.exists()){ + isDele = file.delete(); + }else{ + isDele = true; + } }catch (Exception e){ e.printStackTrace(); isDele = false; diff --git a/src/main/java/cn/hellohao/utils/progress/MyProgress.java b/src/main/java/cn/hellohao/utils/progress/MyProgress.java index b7b31bc..561a39c 100644 --- a/src/main/java/cn/hellohao/utils/progress/MyProgress.java +++ b/src/main/java/cn/hellohao/utils/progress/MyProgress.java @@ -4,26 +4,22 @@ import java.util.ArrayList; import java.util.List; public class MyProgress { - - //删除图片时候的数据 private int delSuccessCount=0;//已经成功的个数 private List delErrorImgListt = new ArrayList<>();//已经失败的图片 - private boolean delOCT=false; //控制开关 + private int delOCT=0; //控制开关 private List delSuccessImgList = new ArrayList<>(); //删除成功的图片 public void InitializeDelImg(){ - //删除图片时候的数据 this.delSuccessCount=0;//已经成功的个数 this.delErrorImgListt = new ArrayList<>();//已经失败的图片 - this.delOCT=false; //控制开关 + this.delOCT=0; //控制开关 0代表false 1代表true this.delSuccessImgList = new ArrayList<>(); //删除成功的图片 } public MyProgress() { } - public MyProgress(int delSuccessCount, List delErrorImgListt, boolean delOCT, List delSuccessImgList) { - + public MyProgress(int delSuccessCount, List delErrorImgListt, int delOCT, List delSuccessImgList) { this.delSuccessCount = delSuccessCount; this.delErrorImgListt = delErrorImgListt; this.delOCT = delOCT; @@ -46,11 +42,11 @@ public class MyProgress { this.delErrorImgListt = delErrorImgListt; } - public boolean getDelOCT() { + public int getDelOCT() { return delOCT; } - public void setDelOCT(boolean delOCT) { + public void setDelOCT(int delOCT) { this.delOCT = delOCT; } @@ -62,13 +58,5 @@ public class MyProgress { this.delSuccessImgList = delSuccessImgList; } - @Override - public String toString() { - return "MyProgress{" + - ", delSuccessCount=" + delSuccessCount + - ", delErrorImgListt=" + delErrorImgListt + - ", delOCT=" + delOCT + - ", delSuccessImgList=" + delSuccessImgList + - '}'; - } + } \ No newline at end of file diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml index e897c2b..a0981b3 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -117,8 +117,8 @@ - INSERT INTO imgdata (id, imgname, imgurl, userid, updatetime,sizes,abnormal,source,imgtype,md5key,imguid,format,about,violation,idname) - VALUES (NULL, #{imgname}, #{imgurl}, #{userid}, #{updatetime},#{sizes},#{abnormal},#{source},#{imgtype},#{md5key},#{imguid},#{format},#{about},null,#{idname}) + INSERT INTO imgdata (id, imgname, imgurl, userid, updatetime,sizes,abnormal,source,imgtype,md5key,imguid,format,about,violation) + VALUES (NULL, #{imgname}, #{imgurl}, #{userid}, #{updatetime},#{sizes},#{abnormal},#{source},#{imgtype},#{md5key},#{imguid},#{format},#{about},null)