diff options
Diffstat (limited to 'src/main/java/com/mesasoft/cn/service/impl')
9 files changed, 1104 insertions, 0 deletions
diff --git a/src/main/java/com/mesasoft/cn/service/impl/AuthServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/AuthServiceImpl.java new file mode 100644 index 0000000..d4d0e53 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/AuthServiceImpl.java @@ -0,0 +1,96 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.dao.AuthDAO; +import com.mesasoft.cn.util.BeanUtils; +import com.mesasoft.cn.config.SettingConfig; +import com.mesasoft.cn.entity.Auth; +import com.mesasoft.cn.model.AuthRecord; +import com.mesasoft.cn.modules.constant.ConfigConsts; +import com.mesasoft.cn.service.IAuthService; +import com.mesasoft.cn.util.ServiceUtils; +import com.zhazhapan.modules.constant.ValueConsts; +import com.zhazhapan.util.Checker; +import com.zhazhapan.util.Formatter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author pantao + * @since 2018/2/1 + */ +@Service +public class AuthServiceImpl implements IAuthService { + + private final AuthDAO authDAO; + + @Autowired + public AuthServiceImpl(AuthDAO authDAO) {this.authDAO = authDAO;} + + @Override + public boolean addAuth(String files, String users, String auths) { + if (Checker.isNotEmpty(files) && Checker.isNotEmpty(users) && Checker.isNotEmpty(auths)) { + String[] file = files.split(ValueConsts.COMMA_SIGN); + String[] user = users.split(ValueConsts.COMMA_SIGN); + for (String f : file) { + long fileId = Formatter.stringToLong(f); + for (String u : user) { + int userId = Formatter.stringToInt(u); + if (Checker.isNull(authDAO.exists(userId, fileId))) { + Auth auth = new Auth(userId, fileId); + auth.setAuth(BeanUtils.getAuth(auths)); + authDAO.insertAuth(auth); + } + } + } + } + return true; + } + + @Override + public boolean batchDelete(String ids) { + return Checker.isNotEmpty(ids) && authDAO.batchDelete(ids); + } + + @Override + public boolean updateAuth(long id, String auths) { + int[] auth = BeanUtils.getAuth(auths); + return authDAO.updateAuthById(id, auth[0], auth[1], auth[2], auth[3], auth[4]); + } + + @Override + public List<AuthRecord> listAuth(String usernameOrEmail, String fileName, int offset) { + long fileId = ServiceUtils.getFileId(fileName); + int userId = ServiceUtils.getUserId(usernameOrEmail); + return authDAO.listAuthBy(ValueConsts.ZERO_INT, userId, fileId, fileName, offset); + } + + @Override + public AuthRecord getByFileIdAndUserId(long fileId, int userId) { + List<AuthRecord> authRecords = authDAO.listAuthBy(ValueConsts.ZERO_INT, userId, fileId, ValueConsts + .EMPTY_STRING, ValueConsts.ZERO_INT); + if (Checker.isNotEmpty(authRecords)) { + return authRecords.get(0); + } + return null; + } + + @Override + public boolean insertDefaultAuth(int userId, long fileId) { + int[] defaultAuth = SettingConfig.getAuth(ConfigConsts.AUTH_DEFAULT_OF_SETTING); + Auth auth = new Auth(userId, fileId); + auth.setAuth(defaultAuth[0], defaultAuth[1], defaultAuth[2], defaultAuth[3], defaultAuth[4]); + return insertAuth(auth); + } + + @Override + public boolean insertAuth(Auth auth) { + return authDAO.insertAuth(auth); + } + + @Override + public boolean removeByFileId(long fileId) { + return authDAO.removeAuthByFileId(fileId); + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/CategoryServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/CategoryServiceImpl.java new file mode 100644 index 0000000..12f9a2d --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/CategoryServiceImpl.java @@ -0,0 +1,62 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.dao.CategoryDAO; +import com.mesasoft.cn.entity.Category; +import com.mesasoft.cn.modules.constant.DefaultValues; +import com.mesasoft.cn.service.ICategoryService; +import com.zhazhapan.util.Checker; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author pantao + * @since 2018/1/30 + */ +@Service +public class CategoryServiceImpl implements ICategoryService { + + private final CategoryDAO categoryDAO; + + @Autowired + public CategoryServiceImpl(CategoryDAO categoryDAO) {this.categoryDAO = categoryDAO;} + + @Override + public boolean insert(String name) { + return Checker.isNotNull(name) && categoryDAO.insertCategory(name); + } + + @Override + public boolean remove(int id) { + return isCategorized(id) && categoryDAO.removeCategoryById(id); + } + + @Override + public boolean update(int id, String name) { + return Checker.isNotEmpty(name) && isCategorized(id) && categoryDAO.updateNameById(id, name); + } + + private boolean isCategorized(int id) { + return !DefaultValues.UNCATEGORIZED.equals(getById(id).getName()); + } + + @Override + public Category getById(int id) { + return categoryDAO.getCategoryById(id); + } + + @Override + public List<Category> list() { + return categoryDAO.listCategory(); + } + + @Override + public int getIdByName(String name) { + try { + return categoryDAO.getIdByName(name); + } catch (Exception e) { + return Integer.MAX_VALUE; + } + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/CommonServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/CommonServiceImpl.java new file mode 100644 index 0000000..05f1d10 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/CommonServiceImpl.java @@ -0,0 +1,59 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.modules.constant.DefaultValues; +import com.mesasoft.cn.config.SettingConfig; +import com.mesasoft.cn.service.ICommonService; +import com.zhazhapan.modules.constant.ValueConsts; +import com.zhazhapan.util.Checker; +import com.zhazhapan.util.FileExecutor; +import com.zhazhapan.util.MailSender; +import com.zhazhapan.util.RandomUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; + +/** + * @author pantao + * @since 2018/1/23 + */ +@Service +public class CommonServiceImpl implements ICommonService { + + private static final String EMAIL_TITLE = "请查收您的验证码"; + private static Logger logger = LoggerFactory.getLogger(CommonServiceImpl.class); + + @Override + public int sendVerifyCode(String email) { + int code = RandomUtils.getRandomInteger(ValueConsts.VERIFY_CODE_FLOOR, ValueConsts.VERIFY_CODE_CEIL); + String content = "<p>您的验证码:" + code + "</p><br/><br/><p>如非本人操作,请忽略本条消息。</p>"; + try { + MailSender.sendMail(email, EMAIL_TITLE, content); + return code; + } catch (Exception e) { + logger.error(e.getMessage()); + return 0; + } + } + + @Override + public String uploadAvatar(MultipartFile multipartFile) { + if (!multipartFile.isEmpty()) { + String name = RandomUtils.getRandomStringOnlyLowerCase(ValueConsts.SIXTEEN_INT) + ValueConsts.DOT_SIGN + + FileExecutor.getFileSuffix(multipartFile.getOriginalFilename()); + if (Checker.isImage(name) && multipartFile.getSize() < ValueConsts.MB * DefaultValues.TWO_INT) { + String path = SettingConfig.getAvatarStoragePath() + ValueConsts.SEPARATOR + name; + try { + FileExecutor.writeByteArrayToFile(new File(path), multipartFile.getBytes()); + return name; + } catch (IOException e) { + logger.error("upload avatar error: " + e.getMessage()); + } + } + } + return ""; + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/ConfigServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/ConfigServiceImpl.java new file mode 100644 index 0000000..1de92b2 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/ConfigServiceImpl.java @@ -0,0 +1,33 @@ +package com.mesasoft.cn.service.impl; + +import com.alibaba.fastjson.JSONObject; +import com.mesasoft.cn.SketchApplication; +import com.mesasoft.cn.modules.constant.ConfigConsts; +import com.mesasoft.cn.service.IConfigService; +import org.springframework.stereotype.Service; + +/** + * @author pantao + * @since 2018/1/22 + */ +@Service +public class ConfigServiceImpl implements IConfigService { + + @Override + public String getGlobalConfig() { + JSONObject jsonObject = (JSONObject) SketchApplication.settings.getObjectUseEval(ConfigConsts + .GLOBAL_OF_SETTINGS).clone(); + jsonObject.remove(ConfigConsts.UPLOAD_PATH_OF_GLOBAL); + jsonObject.remove(ConfigConsts.TOKEN_PATH_OF_GLOBAL); + jsonObject.remove(ConfigConsts.UPLOAD_FORM_OF_SETTING); + return jsonObject.toString(); + } + + @Override + public String getUserConfig() { + JSONObject jsonObject = (JSONObject) SketchApplication.settings.getObjectUseEval(ConfigConsts.USER_OF_SETTINGS) + .clone(); + jsonObject.remove(ConfigConsts.EMAIL_CONFIG_OF_USER); + return jsonObject.toString(); + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/DownloadedServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/DownloadedServiceImpl.java new file mode 100644 index 0000000..3c2b546 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/DownloadedServiceImpl.java @@ -0,0 +1,42 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.dao.DownloadedDAO; +import com.mesasoft.cn.model.DownloadRecord; +import com.mesasoft.cn.service.IDownloadedService; +import com.mesasoft.cn.util.ServiceUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author pantao + * @since 2018/2/1 + */ +@Service +public class DownloadedServiceImpl implements IDownloadedService { + + private final DownloadedDAO downloadDAO; + + @Autowired + public DownloadedServiceImpl(DownloadedDAO downloadDAO) { + this.downloadDAO = downloadDAO; + } + + @Override + public void insertDownload(int userId, long fileId) { + downloadDAO.insertDownload(userId, fileId); + } + + @Override + public void removeByFileId(long fileId) { + downloadDAO.removeByFileId(fileId); + } + + @SuppressWarnings("unchecked") + @Override + public List<DownloadRecord> list(String user, String file, String category, int offset) { + return (List<DownloadRecord>) ServiceUtils.invokeFileFilter(downloadDAO, "listDownloadedBy", user, file, + category, offset); + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/FileManagerServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/FileManagerServiceImpl.java new file mode 100644 index 0000000..0ae179b --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/FileManagerServiceImpl.java @@ -0,0 +1,236 @@ +package com.mesasoft.cn.service.impl; + +import cn.hutool.core.util.ZipUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.mesasoft.cn.modules.constant.DefaultValues; +import com.mesasoft.cn.service.IFileManagerService; +import com.zhazhapan.modules.constant.ValueConsts; +import com.zhazhapan.util.Checker; +import com.zhazhapan.util.FileExecutor; +import com.zhazhapan.util.Formatter; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import javax.swing.filechooser.FileSystemView; +import java.io.File; +import java.io.IOException; +import java.util.Date; + +/** + * @author pantao + * @since 2018/1/29 + */ +@Service +public class FileManagerServiceImpl implements IFileManagerService { + + private static Logger logger = Logger.getLogger(FileManagerServiceImpl.class); + + @Override + public void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException { + File zip = ZipUtil.zip(new File(ValueConsts.USER_DESKTOP + File.separator + destFile), ValueConsts.FALSE, + FileExecutor.getFiles(items)); + if (zip.exists()) { + response.getOutputStream().write(FileExecutor.readFileToByteArray(zip)); + FileExecutor.deleteFile(zip); + } + } + + @Override + public JSONObject upload(String destination, MultipartFile... files) { + System.out.println(files.length); + if (Checker.isNotEmpty(files)) { + if (Checker.isWindows() && destination.length() < ValueConsts.TWO_INT) { + destination = "C:"; + } + for (MultipartFile file : files) { + if (Checker.isNotNull(file) && !file.isEmpty()) { + try { + file.transferTo(new File(destination + File.separator + file.getOriginalFilename())); + } catch (IOException e) { + logger.error(e.getMessage()); + return getBasicResponse(ValueConsts.FALSE); + } + } + } + } + return getBasicResponse(ValueConsts.TRUE); + } + + @Override + public JSONObject extract(JSONObject object) { + String destination = object.getString("destination") + File.separator + object.getString("folderName"); + String zipFile = object.getString("item"); + return getBasicResponse(ZipUtil.unzip(zipFile, destination).exists()); + } + + @Override + public JSONObject compress(JSONObject object) { + JSONArray array = object.getJSONArray("items"); + File[] files = new File[array.size()]; + int i = 0; + for (Object file : array) { + files[i++] = new File(file.toString()); + } + String dest = object.getString("destination"); + String name = object.getString("compressedFilename"); + File zip = ZipUtil.zip(new File(dest + File.separator + name), ValueConsts.FALSE, files); + return getBasicResponse(zip.exists()); + } + + @Override + public JSONObject setPermission(JSONObject object) { + if (Checker.isLinux()) { + JSONArray array = object.getJSONArray("items"); + int code = object.getInteger("permsCode"); + for (Object file : array) { + try { + Runtime.getRuntime().exec("chmod -R " + code + " " + file.toString()); + } catch (IOException e) { + logger.error(e.getMessage()); + return getBasicResponse(ValueConsts.FALSE); + } + } + } + return getBasicResponse(ValueConsts.TRUE); + } + + @Override + public JSONObject createFolder(JSONObject object) { + String folder = object.getString("newPath"); + return getBasicResponse(FileExecutor.createFolder(folder)); + } + + @Override + public String getContent(JSONObject object) { + String fileName = object.getString("item"); + try { + return FileExecutor.readFile(fileName); + } catch (IOException e) { + logger.error(e.getMessage()); + return ""; + } + } + + @Override + public JSONObject edit(JSONObject object) { + String file = object.getString("item"); + String content = object.getString("content"); + try { + FileExecutor.saveFile(file, content); + return getBasicResponse(ValueConsts.TRUE); + } catch (IOException e) { + logger.error(e.getMessage()); + return getBasicResponse(ValueConsts.FALSE); + } + } + + @Override + public JSONObject remove(JSONObject object) { + JSONArray array = object.getJSONArray("items"); + array.forEach(file -> FileExecutor.deleteFile(file.toString())); + return getBasicResponse(ValueConsts.TRUE); + } + + @Override + public JSONObject copy(JSONObject object) { + JSONArray array = object.getJSONArray("items"); + String dest = object.getString("newPath"); + File[] files = new File[array.size()]; + int i = 0; + for (Object file : array) { + files[i++] = new File(file.toString()); + } + try { + FileExecutor.copyFiles(files, dest); + return getBasicResponse(ValueConsts.TRUE); + } catch (IOException e) { + logger.error(e.getMessage()); + return getBasicResponse(ValueConsts.FALSE); + } + } + + @Override + public JSONObject move(JSONObject object) { + JSONArray array = object.getJSONArray("items"); + String dest = object.getString("newPath"); + for (Object file : array) { + try { + FileExecutor.moveToDirectory(new File(file.toString()), new File(dest), ValueConsts.TRUE); + } catch (IOException e) { + logger.error(e.getMessage()); + return getBasicResponse(ValueConsts.FALSE); + } + } + return getBasicResponse(ValueConsts.TRUE); + } + + @Override + public JSONObject rename(JSONObject object) { + String fileName = object.getString("item"); + String newFileName = object.getString("newItemPath"); + FileExecutor.renameTo(fileName, newFileName); + return getBasicResponse(ValueConsts.TRUE); + } + + @Override + public JSONArray list(JSONObject object) { + String path = object.getString("path"); + JSONArray array = new JSONArray(); + File[] files = null; + if (Checker.isWindows()) { + if (Checker.isNotEmpty(path) && path.startsWith(ValueConsts.SPLASH_STRING)) { + path = path.substring(1); + } + if (Checker.isEmpty(path)) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + File[] fs = File.listRoots(); + for (File file : fs) { + if (file.getTotalSpace() > 0) { + String displayName = fsv.getSystemDisplayName(file); + int len = displayName.length(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", displayName.substring(len - 3, len - 1)); + jsonObject.put("rights", "----------"); + jsonObject.put("size", file.getTotalSpace() - file.getFreeSpace()); + jsonObject.put("date", Formatter.datetimeToString(new Date(file.lastModified()))); + jsonObject.put("type", file.isDirectory() ? "dir" : "file"); + array.add(jsonObject); + } + } + } else if (path.startsWith(DefaultValues.COLON, 1)) { + files = FileExecutor.listFile(path.endsWith(DefaultValues.COLON) ? path + File.separator : path); + } else { + logger.error("path error"); + } + } else { + files = FileExecutor.listFile(Checker.isEmpty(path) ? "/" : (path.startsWith("/") ? path : "/" + path)); + } + if (Checker.isNotNull(files)) { + for (File file : files) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", file.getName()); + jsonObject.put("rights", "----------"); + jsonObject.put("size", file.length()); + jsonObject.put("date", Formatter.datetimeToString(new Date(file.lastModified()))); + jsonObject.put("type", file.isDirectory() ? "dir" : "file"); + array.add(jsonObject); + } + } + return array; + } + + private JSONObject getBasicResponse(boolean isSuccess) { + JSONObject jsonObject = new JSONObject(); + if (isSuccess) { + jsonObject.put("success", true); + jsonObject.put("error", null); + } else { + jsonObject.put("success", null); + jsonObject.put("error", "服务器异常"); + } + return jsonObject; + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/FileServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/FileServiceImpl.java new file mode 100644 index 0000000..2c6e6e9 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/FileServiceImpl.java @@ -0,0 +1,383 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.SketchApplication; +import com.mesasoft.cn.dao.DownloadedDAO; +import com.mesasoft.cn.dao.FileDAO; +import com.mesasoft.cn.util.BeanUtils; +import com.mesasoft.cn.config.SettingConfig; +import com.mesasoft.cn.entity.Category; +import com.mesasoft.cn.entity.File; +import com.mesasoft.cn.entity.User; +import com.mesasoft.cn.model.AuthRecord; +import com.mesasoft.cn.model.BaseAuthRecord; +import com.mesasoft.cn.model.FileBasicRecord; +import com.mesasoft.cn.model.FileRecord; +import com.mesasoft.cn.modules.constant.ConfigConsts; +import com.mesasoft.cn.modules.constant.DefaultValues; +import com.mesasoft.cn.service.IAuthService; +import com.mesasoft.cn.service.ICategoryService; +import com.mesasoft.cn.service.IFileService; +import com.mesasoft.cn.util.ServiceUtils; +import com.zhazhapan.modules.constant.ValueConsts; +import com.zhazhapan.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.Date; +import java.util.List; +import java.util.regex.Pattern; + +/** + * @author pantao + * @since 2018/1/29 + */ +@Service +public class FileServiceImpl implements IFileService { + + private final static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class); + + private static final String FILE_SUFFIX = "{fileSuffix}"; + + private static final String RANDOM_ID = "{randomId}"; + + private static final String YEAR = "{year}"; + + private static final String MONTH = "{month}"; + + private static final String DAY = "{day}"; + + private static final String AUTHOR = "{author}"; + + private static final String FILE_NAME = "{fileName}"; + + private static final String CATEGORY_NAME = "{categoryName}"; + + private final FileDAO fileDAO; + + private final ICategoryService categoryService; + + private final IAuthService authService; + + private final DownloadedDAO downloadDAO; + + @Autowired + public FileServiceImpl(FileDAO fileDAO, ICategoryService categoryService, IAuthService authService, + DownloadedDAO downloadDAO) { + this.fileDAO = fileDAO; + this.categoryService = categoryService; + this.authService = authService; + this.downloadDAO = downloadDAO; + } + + @Override + public boolean updateAuth(long id, String auth) { + int[] au = BeanUtils.getAuth(auth); + return fileDAO.updateAuthById(id, au[0], au[1], au[2], au[3], au[4]); + } + + @Override + public BaseAuthRecord getAuth(long id) { + return fileDAO.getAuth(id); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = + Exception.class) + public boolean deleteFiles(String ids) { + if (Checker.isNotEmpty(ids)) { + String[] id = ids.split(ValueConsts.COMMA_SIGN); + for (String s : id) { + long fileId = Formatter.stringToLong(s); + String localUrl = fileDAO.getLocalUrlById(fileId); + FileExecutor.deleteFile(localUrl); + removeById(fileId); + } + return true; + } + return false; + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = + Exception.class) + public boolean[] updateUrl(int id, String oldLocalUrl, String localUrl, String visitUrl) { + boolean[] b = new boolean[]{false, false}; + boolean canUpdateLocalUrl = Checker.isExists(oldLocalUrl) && Checker.isNotEmpty(localUrl) && Checker + .isNotExists(localUrl) && !localUrlExists(localUrl); + if (canUpdateLocalUrl) { + FileExecutor.renameTo(oldLocalUrl, localUrl); + fileDAO.updateLocalUrlById(id, localUrl); + b[0] = true; + } + if (Checker.isNotEmpty(visitUrl) && !visitUrlExists(visitUrl)) { + fileDAO.updateVisitUrlById(id, visitUrl); + b[1] = true; + } + return b; + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = + Exception.class) + public boolean updateFileInfo(long id, User user, String name, String category, String tag, String description) { + File file = fileDAO.getById(id); + if (Checker.isNotNull(file) && file.getIsUpdatable() == 1) { + AuthRecord authRecord = authService.getByFileIdAndUserId(id, user.getId()); + String suffix = FileExecutor.getFileSuffix(name); + boolean canUpdate = (Checker.isNull(authRecord) ? user.getIsUpdatable() == 1 : + authRecord.getIsUpdatable() == 1) && Checker.isNotEmpty(name) && Pattern.compile(SketchApplication.settings.getStringUseEval(ConfigConsts.FILE_SUFFIX_MATCH_OF_SETTING)).matcher(suffix).matches(); + if (canUpdate) { + String localUrl = file.getLocalUrl(); + java.io.File newFile = new java.io.File(localUrl); + String visitUrl = file.getVisitUrl(); + String newLocalUrl = localUrl.substring(0, localUrl.lastIndexOf(ValueConsts.SEPARATOR) + 1) + name; + String newVisitUrl = visitUrl.substring(0, visitUrl.lastIndexOf(ValueConsts.SPLASH_STRING) + 1) + name; + file.setName(name); + file.setSuffix(suffix); + file.setLocalUrl(newLocalUrl); + file.setVisitUrl(newVisitUrl); + file.setCategoryId(categoryService.getIdByName(category)); + file.setTag(tag); + file.setDescription(description); + boolean isValid = (localUrl.endsWith(ValueConsts.SEPARATOR + name) || (!Checker.isExists(newLocalUrl) + && !localUrlExists(newLocalUrl) && !visitUrlExists(newVisitUrl))); + if (isValid && fileDAO.updateFileInfo(file)) { + return newFile.renameTo(new java.io.File(newLocalUrl)); + } + } + } + return false; + } + + @Override + public boolean removeFile(User user, long fileId) { + File file = fileDAO.getById(fileId); + boolean isDeleted = false; + if (Checker.isNotNull(file) && file.getIsDeletable() == 1) { + AuthRecord authRecord = authService.getByFileIdAndUserId(fileId, user.getId()); + String localUrl = fileDAO.getLocalUrlById(fileId); + isDeleted = (Checker.isNull(authRecord) ? user.getIsDeletable() == 1 : authRecord.getIsDeletable() == 1) + && removeById(fileId); + if (isDeleted) { + FileExecutor.deleteFile(localUrl); + } + } + return isDeleted; + } + + @Override + public List<FileRecord> listUserDownloaded(int userId, int offset, String search) { + return fileDAO.listUserDownloaded(userId, offset, search); + } + + @Override + public List<FileRecord> listUserUploaded(int userId, int offset, String search) { + return fileDAO.listUserUploaded(userId, offset, search); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = + Exception.class) + public boolean removeById(long id) { + downloadDAO.removeByFileId(id); + authService.removeByFileId(id); + return fileDAO.removeById(id); + } + + @Override + public boolean removeByVisitUrl(String visitUrl) { + long fileId = fileDAO.getIdByVisitUrl(visitUrl); + return removeById(fileId); + } + + @Override + public boolean removeByLocalUrl(String localUrl) { + long fileId = fileDAO.getIdByLocalUrl(localUrl); + return removeById(fileId); + } + + @Override + public String getResource(String visitUrl, HttpServletRequest request) { + logger.info("visit url: " + visitUrl); + boolean downloadable = SketchApplication.settings.getBooleanUseEval(ConfigConsts + .ANONYMOUS_DOWNLOADABLE_OF_SETTING); + User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING); + File file = fileDAO.getFileByVisitUrl(visitUrl); + AuthRecord authRecord = null; + if (Checker.isNotNull(file)) { + authRecord = authService.getByFileIdAndUserId(file.getId(), Checker.isNull(user) ? 0 : user.getId()); + } + boolean canDownload = Checker.isNotNull(file) && file.getIsDownloadable() == 1 && (downloadable || (Checker + .isNull(authRecord) ? (Checker.isNotNull(user) && user.getIsDownloadable() == 1) : authRecord + .getIsDownloadable() == 1)); + if (canDownload) { + fileDAO.updateDownloadTimesById(file.getId()); + if (Checker.isNotNull(user)) { + downloadDAO.insertDownload(user.getId(), file.getId()); + } + return file.getLocalUrl(); + } + return ""; + } + + @Override + public String getLocalUrlByVisitUrl(String visitUrl) { + return fileDAO.getLocalUrlByVisitUrl(Checker.checkNull(visitUrl)); + } + + @Override + public List<FileRecord> listAll(int userId, int offset, int categoryId, String orderBy, String search) { + return fileDAO.listAll(userId, offset, categoryId, orderBy, search); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = + Exception.class) + public boolean upload(int categoryId, String tag, String description, String prefix, MultipartFile multipartFile, + User user) { + if (user.getIsUploadable() == 1) { + String name = multipartFile.getOriginalFilename(); + String suffix = FileExecutor.getFileSuffix(name); + String localUrl = SettingConfig.getUploadStoragePath() + ValueConsts.SEPARATOR + name; + Category category = categoryService.getById(categoryId); + long maxSize = Formatter.sizeToLong(SketchApplication.settings.getStringUseEval(ConfigConsts + .FILE_MAX_SIZE_OF_SETTING)); + long size = multipartFile.getSize(); + boolean fileExists = localUrlExists(localUrl); + //检测标签是否合法 + if (SketchApplication.settings.getBooleanUseEval(ConfigConsts.TAG_REQUIRE_OF_SETTING)) { + String[] tags = Checker.checkNull(tag).split(ValueConsts.SPACE); + if (tags.length <= SketchApplication.settings.getIntegerUseEval(ConfigConsts.TAG_SIZE_OF_SETTING)) { + int maxLength = SketchApplication.settings.getIntegerUseEval(ConfigConsts.TAG_LENGTH_OF_SETTING); + for (String t : tags) { + if (t.length() > maxLength) { + return false; + } + } + } else { + return false; + } + } + //是否可以上传 + boolean canUpload = !multipartFile.isEmpty() && size <= maxSize && Pattern.compile(SketchApplication + .settings.getStringUseEval(ConfigConsts.FILE_SUFFIX_MATCH_OF_SETTING)).matcher(suffix).matches() + && (Checker.isNotExists(localUrl) || !fileExists || SketchApplication.settings.getBooleanUseEval + (ConfigConsts.FILE_COVER_OF_SETTING)); + logger.info("is empty [" + multipartFile.isEmpty() + "], file size [" + size + "], max file size [" + + maxSize + "]"); + if (canUpload) { + String visitUrl = getRegularVisitUrl(Checker.isNotEmpty(prefix) && user.getPermission() > 1 ? prefix + : SketchApplication.settings.getStringUseEval(ConfigConsts.CUSTOM_LINK_RULE_OF_SETTING), user, + name, suffix, category); + if (fileExists) { + removeByLocalUrl(localUrl); + } + if (visitUrlExists(visitUrl)) { + removeByVisitUrl(visitUrl); + } + try { + multipartFile.transferTo(new java.io.File(localUrl)); + logger.info("local url of upload file: " + localUrl); + File file = new File(name, suffix, localUrl, visitUrl, WebUtils.scriptFilter(description), + WebUtils.scriptFilter(tag), user.getId(), categoryId); + int[] auth = SettingConfig.getAuth(ConfigConsts.FILE_DEFAULT_AUTH_OF_SETTING); + file.setAuth(auth[0], auth[1], auth[2], auth[3], auth[4]); + boolean isSuccess = fileDAO.insertFile(file); + if (isSuccess) { + long fileId = fileDAO.getIdByLocalUrl(localUrl); + if (fileId > 0) { + authService.insertDefaultAuth(user.getId(), fileId); + } + } else { + FileExecutor.deleteFile(localUrl); + } + return isSuccess; + } catch (Exception e) { + FileExecutor.deleteFile(localUrl); + logger.error("save file error: " + e.getMessage()); + } + } + } + return false; + } + + private String getRegularVisitUrl(String customUrl, User user, String fileName, String suffix, Category category) { + Date date = new Date(); + suffix = suffix.startsWith(".") ? "" : "." + suffix; + if (Checker.isNotEmpty(customUrl)) { + try { + customUrl = URLDecoder.decode(customUrl, "utf-8"); + } catch (UnsupportedEncodingException e) { + logger.error(e.getMessage()); + } + } + if (!customUrl.contains(FILE_NAME) && !customUrl.contains(RANDOM_ID)) { + customUrl += (customUrl.endsWith("/") ? "" : "/") + fileName; + } + customUrl = customUrl.replace(YEAR, DateUtils.getYear(date)).replace(MONTH, DateUtils.getMonth(date)).replace + (DAY, DateUtils.getDay(date)).replace(AUTHOR, user.getUsername()).replace(FILE_NAME, fileName) + .replace(CATEGORY_NAME, Checker.checkNull(Checker.isNull(category) ? "uncategorized" : category + .getName())).replace(RANDOM_ID, String.valueOf(RandomUtils.getRandomInteger(ValueConsts + .NINE_INT))).replace(FILE_SUFFIX, suffix); + return "/file" + (customUrl.startsWith("/") ? "" : "/") + customUrl; + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = + Exception.class) + public boolean shareFiles(String prefix, String files, User user) { + if (Checker.isNotEmpty(files)) { + String[] paths = files.split(ValueConsts.COMMA_SIGN); + for (String path : paths) { + java.io.File f = new java.io.File(path); + String name = f.getName(); + String suffix = FileExecutor.getFileSuffix(name); + String visitUrl = getRegularVisitUrl(prefix, user, name, suffix, null); + if (f.exists() && f.isFile() && !localUrlExists(path) && !visitUrlExists(visitUrl)) { + File file = new File(name, suffix, path, visitUrl, ValueConsts.EMPTY_STRING, + ValueConsts.EMPTY_STRING, user.getId(), + categoryService.getIdByName(DefaultValues.UNCATEGORIZED)); + file.setAuth(ValueConsts.ONE_INT, ValueConsts.ZERO_INT, ValueConsts.ZERO_INT, + ValueConsts.ZERO_INT, ValueConsts.ONE_INT); + fileDAO.insertFile(file); + } + } + } + return true; + } + + @Override + public boolean localUrlExists(String localUrl) { + return fileDAO.checkLocalUrl(localUrl) > 0; + } + + @Override + public boolean visitUrlExists(String visitUrl) { + return fileDAO.checkVisitUrl(visitUrl) > 0; + } + + @Override + public long getFileId(String localUrl) { + try { + return fileDAO.getIdByLocalUrl(localUrl); + } catch (Exception e) { + return 0; + } + } + + @SuppressWarnings("unchecked") + @Override + public List<FileBasicRecord> listBasicAll(String user, String file, String category, int offset) { + return (List<FileBasicRecord>) ServiceUtils.invokeFileFilter(fileDAO, "listBasicBy", user, file, category, + offset); + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/UploadedServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/UploadedServiceImpl.java new file mode 100644 index 0000000..a02afff --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/UploadedServiceImpl.java @@ -0,0 +1,30 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.dao.UploadedDAO; +import com.mesasoft.cn.model.UploadedRecord; +import com.mesasoft.cn.service.IUploadedService; +import com.mesasoft.cn.util.ServiceUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author pantao + * @since 2018/2/28 + */ +@Service +public class UploadedServiceImpl implements IUploadedService { + + private final UploadedDAO uploadedDAO; + + @Autowired + public UploadedServiceImpl(UploadedDAO uploadedDAO) {this.uploadedDAO = uploadedDAO;} + + @SuppressWarnings("unchecked") + @Override + public List<UploadedRecord> list(String user, String file, String category, int offset) { + return (List<UploadedRecord>) ServiceUtils.invokeFileFilter(uploadedDAO, "listUploadedBy", user, file, + category, offset); + } +} diff --git a/src/main/java/com/mesasoft/cn/service/impl/UserServiceImpl.java b/src/main/java/com/mesasoft/cn/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..8974f95 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/impl/UserServiceImpl.java @@ -0,0 +1,163 @@ +package com.mesasoft.cn.service.impl; + +import com.mesasoft.cn.SketchApplication; +import com.mesasoft.cn.dao.UserDAO; +import com.mesasoft.cn.util.BeanUtils; +import com.mesasoft.cn.config.SettingConfig; +import com.mesasoft.cn.config.TokenConfig; +import com.mesasoft.cn.entity.User; +import com.mesasoft.cn.modules.constant.ConfigConsts; +import com.mesasoft.cn.service.IUserService; +import com.zhazhapan.modules.constant.ValueConsts; +import com.zhazhapan.util.Checker; +import com.zhazhapan.util.DateUtils; +import com.zhazhapan.util.MailSender; +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.regex.Pattern; + +/** + * @author pantao + * @since 2018/1/22 + */ +@Service +public class UserServiceImpl implements IUserService { + + private final UserDAO userDAO; + + private Logger logger = Logger.getLogger(UserServiceImpl.class); + + @Autowired + public UserServiceImpl(UserDAO userDAO) {this.userDAO = userDAO;} + + @Override + public boolean updatePermission(int id, int permission) { + return userDAO.updatePermission(id, permission > 2 ? 2 : permission); + } + + @Override + public boolean resetPassword(int id, String password) { + boolean result = Checker.isNotEmpty(password) && userDAO.updatePasswordById(id, password); + if (result) { + TokenConfig.removeTokenByValue(id); + try { + MailSender.sendMail(getUserById(id).getEmail(), "密码重置通知", "您的密码已被管理员重置为:" + password); + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + return result; + } + + @Override + public boolean updateFileAuth(int id, String auths) { + int[] auth = BeanUtils.getAuth(auths); + return userDAO.updateAuthById(id, auth[0], auth[1], auth[2], auth[3], auth[4]); + } + + @Override + public List<User> listUser(int permission, String condition, int offset) { + return userDAO.listUserBy(permission, condition, offset); + } + + @Override + public User login(String loginName, String password, String token, HttpServletResponse response) { + boolean allowLogin = SketchApplication.settings.getBooleanUseEval(ConfigConsts.ALLOW_LOGIN_OF_SETTINGS); + User user = null; + if (allowLogin) { + if (Checker.isNotEmpty(token) && SketchApplication.tokens.containsKey(token)) { + user = userDAO.getUserById(SketchApplication.tokens.get(token)); + if (Checker.isNotNull(response)) { + Cookie cookie = new Cookie(ValueConsts.TOKEN_STRING, TokenConfig.generateToken(token, user.getId + ())); + cookie.setMaxAge(30 * 24 * 60 * 60); + response.addCookie(cookie); + } + } + if (Checker.isNull(user) && Checker.isNotEmpty(loginName) && Checker.isNotEmpty(password)) { + user = userDAO.login(loginName, password); + if (Checker.isNotNull(user)) { + TokenConfig.removeTokenByValue(user.getId()); + } + } + updateUserLoginTime(user); + } + return user; + } + + @Override + public boolean register(String username, String email, String password) { + boolean allowRegister = SketchApplication.settings.getBooleanUseEval(ConfigConsts.ALLOW_REGISTER_OF_SETTINGS); + if (allowRegister) { + boolean isValid = Checker.isEmail(email) && checkPassword(password) && Pattern.compile(SketchApplication.settings + .getStringUseEval(ConfigConsts.USERNAME_PATTERN_OF_SETTINGS)).matcher(username).matches(); + if (isValid) { + User user = new User(username, ValueConsts.EMPTY_STRING, email, password); + int[] auth = SettingConfig.getAuth(ConfigConsts.USER_DEFAULT_AUTH_OF_SETTING); + user.setAuth(auth[0], auth[1], auth[2], auth[3], auth[4]); + return userDAO.insertUser(user); + } + } + return false; + } + + @Override + public boolean resetPasswordByEmail(String email, String password) { + return Checker.isEmail(email) && checkPassword(password) && userDAO.updatePasswordByEmail(password, email); + } + + @Override + public boolean checkPassword(String password) { + int min = SketchApplication.settings.getIntegerUseEval(ConfigConsts.PASSWORD_MIN_LENGTH_OF_SETTINGS); + int max = SketchApplication.settings.getIntegerUseEval(ConfigConsts.PASSWORD_MAX_LENGTH_OF_SETTINGS); + return Checker.isLimited(password, min, max); + } + + @Override + public boolean emailExists(String email) { + return Checker.isEmail(email) && userDAO.checkEmail(email) > 0; + } + + @Override + public boolean updateBasicInfoById(int id, String avatar, String realName, String email) { + return Checker.isEmail(email) && userDAO.updateBasicInfo(id, Checker.checkNull(avatar), Checker.checkNull + (realName), email); + } + + @Override + public int getUserId(String usernameOrEmail) { + try { + return userDAO.getUserId(Checker.checkNull(usernameOrEmail)); + } catch (Exception e) { + return Integer.MAX_VALUE; + } + } + + @Override + public boolean usernameExists(String username) { + return Checker.isNotEmpty(username) && userDAO.checkUsername(username) > 0; + } + + @Override + public User getUserById(int id) { + return userDAO.getUserById(id); + } + + @Override + public void updateUserLoginTime(User user) { + if (Checker.isNotNull(user)) { + user.setLastLoginTime(DateUtils.getCurrentTimestamp()); + userDAO.updateUserLoginTime(user.getId()); + } + } + + @Override + public boolean updatePasswordById(String password, int id) { + return checkPassword(password) && userDAO.updatePasswordById(id, password); + } +} |
