diff options
| author | zhanghongqing <[email protected]> | 2022-08-09 16:54:16 +0800 |
|---|---|---|
| committer | zhanghongqing <[email protected]> | 2022-08-09 16:54:16 +0800 |
| commit | b3fa11d4b1b5a68d7b04fde5eb6cfbda557927eb (patch) | |
| tree | a49d344e49fc427fbf4cf00aa4963c4d04cd98a4 /src/main/java/com/mesasoft/cn/service | |
| parent | d8a2be0d094ac9ba2d47c81ebf03b3fe6e34a078 (diff) | |
Diffstat (limited to 'src/main/java/com/mesasoft/cn/service')
18 files changed, 1899 insertions, 0 deletions
diff --git a/src/main/java/com/mesasoft/cn/service/IAuthService.java b/src/main/java/com/mesasoft/cn/service/IAuthService.java new file mode 100644 index 0000000..4f1759c --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IAuthService.java @@ -0,0 +1,92 @@ +package com.mesasoft.cn.service; + +import com.mesasoft.cn.entity.Auth; +import com.mesasoft.cn.model.AuthRecord; + +import java.util.List; + +/** + * @author pantao + * @since 2018/2/1 + */ +public interface IAuthService { + + /** + * 添加权限集 + * + * @param files 文件 + * @param users 用户 + * @param auths 权限集 + * + * @return 是否添加成功 + */ + boolean addAuth(String files, String users, String auths); + + /** + * 批量删除权限记录 + * + * @param ids 权限编号集 + * + * @return 是否删除成功 + */ + boolean batchDelete(String ids); + + /** + * 更新权限 + * + * @param id 权限编号 + * @param auths 权限 + * + * @return 是否更新成功 + */ + boolean updateAuth(long id, String auths); + + /** + * 获取权限表数据 + * + * @param usernameOrEmail 用户名或邮箱 + * @param fileName 文件名 + * @param offset 偏移 + * + * @return {@link List} + */ + List<AuthRecord> listAuth(String usernameOrEmail, String fileName, int offset); + + /** + * 获取一个权限 + * + * @param fileId 文件编号 + * @param userId 用户编号 + * + * @return {@link AuthRecord} + */ + AuthRecord getByFileIdAndUserId(long fileId, int userId); + + /** + * 添加一个默认权限 + * + * @param userId 用户编号 + * @param fileId 文件编号 + * + * @return 是否添加成功 + */ + boolean insertDefaultAuth(int userId, long fileId); + + /** + * 添加一个权限 + * + * @param auth {@link Auth} + * + * @return 是否添加成功 + */ + boolean insertAuth(Auth auth); + + /** + * 通过文件编号删除权限 + * + * @param fileId 文件编号 + * + * @return 是否删除成功 + */ + boolean removeByFileId(long fileId); +} diff --git a/src/main/java/com/mesasoft/cn/service/ICategoryService.java b/src/main/java/com/mesasoft/cn/service/ICategoryService.java new file mode 100644 index 0000000..bf85404 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/ICategoryService.java @@ -0,0 +1,65 @@ +package com.mesasoft.cn.service; + +import com.mesasoft.cn.entity.Category; + +import java.util.List; + +/** + * @author pantao + * @since 2018/1/30 + */ +public interface ICategoryService { + + /** + * 添加一个分类 + * + * @param name 分类名称 + * + * @return 是否添加成功 + */ + boolean insert(String name); + + /** + * 删除一个分类 + * + * @param id 分类编号 + * + * @return 是否删除成功 + */ + boolean remove(int id); + + /** + * 更新分类 + * + * @param id 分类编号 + * @param name 分类名称 + * + * @return 是否更新成功 + */ + boolean update(int id, String name); + + /** + * 获取一个分类 + * + * @param id 分类编号 + * + * @return {@link Category} + */ + Category getById(int id); + + /** + * 获取所有的分类 + * + * @return {@link List} + */ + List<Category> list(); + + /** + * 通过分类名获取ID + * + * @param name 分类名 + * + * @return {@link Integer} + */ + int getIdByName(String name); +} diff --git a/src/main/java/com/mesasoft/cn/service/ICommonService.java b/src/main/java/com/mesasoft/cn/service/ICommonService.java new file mode 100644 index 0000000..de5fbc4 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/ICommonService.java @@ -0,0 +1,28 @@ +package com.mesasoft.cn.service; + +import org.springframework.web.multipart.MultipartFile; + +/** + * @author pantao + * @since 2018/1/23 + */ +public interface ICommonService { + + /** + * 发送验证码 + * + * @param email 邮箱 + * + * @return 验证码 + */ + int sendVerifyCode(String email); + + /** + * 上传头像 + * + * @param multipartFile 头像文件 + * + * @return 头像文件名 + */ + String uploadAvatar(MultipartFile multipartFile); +} diff --git a/src/main/java/com/mesasoft/cn/service/IConfigService.java b/src/main/java/com/mesasoft/cn/service/IConfigService.java new file mode 100644 index 0000000..e5acfef --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IConfigService.java @@ -0,0 +1,22 @@ +package com.mesasoft.cn.service; + +/** + * @author pantao + * @since 2018/1/22 + */ +public interface IConfigService { + + /** + * 获取全局配置 + * + * @return {@link String} + */ + String getGlobalConfig(); + + /** + * 获取用户配置 + * + * @return {@link String} + */ + String getUserConfig(); +} diff --git a/src/main/java/com/mesasoft/cn/service/IDownloadedService.java b/src/main/java/com/mesasoft/cn/service/IDownloadedService.java new file mode 100644 index 0000000..bb47ecd --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IDownloadedService.java @@ -0,0 +1,39 @@ +package com.mesasoft.cn.service; + +import com.mesasoft.cn.model.DownloadRecord; + +import java.util.List; + +/** + * @author pantao + * @since 2018/2/1 + */ +public interface IDownloadedService { + + /** + * 添加下载记录 + * + * @param userId 用户编号 + * @param fileId 文件编号 + */ + void insertDownload(int userId, long fileId); + + /** + * 通过文件编号删除下载记录 + * + * @param fileId 文件编号 + */ + void removeByFileId(long fileId); + + /** + * 获取所有下载记录 + * + * @param user 用户名或邮箱 + * @param category 分类名称 + * @param file 文件名 + * @param offset 偏移 + * + * @return {@link DownloadRecord} + */ + List<DownloadRecord> list(String user, String file, String category, int offset); +} diff --git a/src/main/java/com/mesasoft/cn/service/IFileManagerService.java b/src/main/java/com/mesasoft/cn/service/IFileManagerService.java new file mode 100644 index 0000000..44c3a4f --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IFileManagerService.java @@ -0,0 +1,136 @@ +package com.mesasoft.cn.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author pantao + * @since 2018/1/29 + */ +public interface IFileManagerService { + + + /** + * 下载多个文件 + * + * @param response {@link HttpServletResponse} + * @param items 文件集 + * @param destFile 目标文件名 + * + * @throws IOException 异常 + */ + void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException; + + /** + * 上传文件(暂时还没有实现) + * + * @param destination 目标文件 + * @param files {@link MultipartFile} + * + * @return {@link JSONObject} + */ + JSONObject upload(String destination, MultipartFile... files); + + /** + * 解压文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject extract(JSONObject object); + + /** + * 压缩文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject compress(JSONObject object); + + /** + * 设置文件权限 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject setPermission(JSONObject object); + + /** + * 创建文件夹 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject createFolder(JSONObject object); + + /** + * 获取文件内容 + * + * @param object {@link JSONObject} + * + * @return 文件内容 + */ + String getContent(JSONObject object); + + /** + * 编辑文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject edit(JSONObject object); + + /** + * 移除文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject remove(JSONObject object); + + /** + * 复制文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject copy(JSONObject object); + + /** + * 移动文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject move(JSONObject object); + + /** + * 重命名 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONObject rename(JSONObject object); + + /** + * 列出文件 + * + * @param object {@link JSONObject} + * + * @return {@link JSONObject} + */ + JSONArray list(JSONObject object); +} diff --git a/src/main/java/com/mesasoft/cn/service/IFileService.java b/src/main/java/com/mesasoft/cn/service/IFileService.java new file mode 100644 index 0000000..3024830 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IFileService.java @@ -0,0 +1,228 @@ +package com.mesasoft.cn.service; + +import com.mesasoft.cn.entity.User; +import com.mesasoft.cn.model.BaseAuthRecord; +import com.mesasoft.cn.model.FileBasicRecord; +import com.mesasoft.cn.model.FileRecord; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.util.List; + +/** + * @author pantao + * @since 2018/1/29 + */ +public interface IFileService { + + /** + * 更新文件权限 + * + * @param id 文件编号 + * @param auth 权限集 + * + * @return 是否更新成功 + */ + boolean updateAuth(long id, String auth); + + /** + * 获取文件权限 + * + * @param id 文件编号 + * + * @return {@link BaseAuthRecord} + */ + BaseAuthRecord getAuth(long id); + + /** + * 批量删除文件 + * + * @param ids 所有文件编号 + * + * @return 是否删除成功 + */ + boolean deleteFiles(String ids); + + /** + * 更新文件路径 + * + * @param id 文件编号 + * @param oldLocalUrl 原本地路径 + * @param localUrl 本地路径 + * @param visitUrl 访问路径 + * + * @return 是否更新成功 + */ + boolean[] updateUrl(int id, String oldLocalUrl, String localUrl, String visitUrl); + + /** + * 更新文件信息 + * + * @param id 文件编号 + * @param user 用户对象 + * @param name 文件名 + * @param category 文件分类 + * @param tag 标签 + * @param description 文件描述 + * + * @return 是否更新成功 + */ + boolean updateFileInfo(long id, User user, String name, String category, String tag, String description); + + /** + * 删除文件,验证权限 + * + * @param user 用户对象 + * @param fileId 文件编号 + * + * @return {@link Boolean} + */ + boolean removeFile(User user, long fileId); + + /** + * 获取用户的下载资源 + * + * @param userId 用户编号 + * @param offset 偏移 + * @param search 搜索 + * + * @return {@link List} + */ + List<FileRecord> listUserDownloaded(int userId, int offset, String search); + + /** + * 获取用户的上传资源 + * + * @param userId 用户编号 + * @param offset 偏移 + * @param search 搜索 + * + * @return {@link List} + */ + List<FileRecord> listUserUploaded(int userId, int offset, String search); + + /** + * 通过编号删除,不验证权限 + * + * @param id 编号 + * + * @return 是否删除成功 + */ + boolean removeById(long id); + + /** + * 通过访问路径删除 + * + * @param visitUrl 访问路径 + * + * @return 是否删除成功 + */ + boolean removeByVisitUrl(String visitUrl); + + /** + * 通过本地路径删除 + * + * @param localUrl 访问路径 + * + * @return 是否删除成功 + */ + boolean removeByLocalUrl(String localUrl); + + /** + * 获取资源 + * + * @param visitUrl 访问路径 + * @param request {@link HttpServletRequest} + * + * @return {@link File} + */ + String getResource(String visitUrl, HttpServletRequest request); + + /** + * 通过访问路径获取本地文件路径 + * + * @param visitUrl 访问路径 + * + * @return {@link String} + */ + String getLocalUrlByVisitUrl(String visitUrl); + + /** + * 获取所有文件 + * + * @param userId 用户编号 + * @param offset 偏移 + * @param categoryId 分类编号 + * @param orderBy 排序方式 + * @param search 搜索 + * + * @return {@link List} + */ + List<FileRecord> listAll(int userId, int offset, int categoryId, String orderBy, String search); + + /** + * 上传文件 + * + * @param categoryId 分类ID + * @param tag 标签 + * @param description 描述 + * @param prefix 自定义前缀 + * @param multipartFile 文件 + * @param user {@link User} + * + * @return 是否上传成功 + */ + boolean upload(int categoryId, String tag, String description, String prefix, MultipartFile multipartFile, User + user); + + /** + * 分享服务器本地文件 + * + * @param prefix 链接前缀 + * @param files 文件 + * @param user 用户对象 + * + * @return 是否添加成功 + */ + boolean shareFiles(String prefix, String files, User user); + + /** + * 本地路径是否存在 + * + * @param localUrl 本地路径 + * + * @return {@link Boolean} + */ + boolean localUrlExists(String localUrl); + + /** + * 访问路径是否存在 + * + * @param visitUrl 访问路径 + * + * @return {@link Boolean} + */ + boolean visitUrlExists(String visitUrl); + + /** + * 通过本地路径获取文件编号 + * + * @param localUrl 本地路径 + * + * @return 文件编号 + */ + long getFileId(String localUrl); + + /** + * 获取所有文件基本信息 + * + * @param user 用户名或邮箱 + * @param category 分类名称 + * @param file 文件名 + * @param offset 偏移 + * + * @return {@link List} + */ + List<FileBasicRecord> listBasicAll(String user, String file, String category, int offset); +} diff --git a/src/main/java/com/mesasoft/cn/service/IUploadedService.java b/src/main/java/com/mesasoft/cn/service/IUploadedService.java new file mode 100644 index 0000000..25cc002 --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IUploadedService.java @@ -0,0 +1,24 @@ +package com.mesasoft.cn.service; + +import com.mesasoft.cn.model.UploadedRecord; + +import java.util.List; + +/** + * @author pantao + * @since 2018/2/28 + */ +public interface IUploadedService { + + /** + * 获取所有上传记录 + * + * @param user 用户名或邮箱 + * @param category 分类名称 + * @param file 文件名 + * @param offset 偏移 + * + * @return {@link List} + */ + List<UploadedRecord> list(String user, String file, String category, int offset); +} diff --git a/src/main/java/com/mesasoft/cn/service/IUserService.java b/src/main/java/com/mesasoft/cn/service/IUserService.java new file mode 100644 index 0000000..485e65d --- /dev/null +++ b/src/main/java/com/mesasoft/cn/service/IUserService.java @@ -0,0 +1,161 @@ +package com.mesasoft.cn.service; + +import com.mesasoft.cn.entity.User; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * @author pantao + * @since 2018/1/22 + */ +public interface IUserService { + + /** + * 更新用户权限 + * + * @param id 用户编号 + * @param permission 权限 + * + * @return 是否更新成功 + */ + boolean updatePermission(int id, int permission); + + /** + * 重置用户密码 + * + * @param id 用户编号 + * @param password 密码 + * + * @return 是否重置成功 + */ + boolean resetPassword(int id, String password); + + /** + * 更新用户权限 + * + * @param id 编号 + * @param auths 操作文件的权限集 + * + * @return 是否更新成功 + */ + boolean updateFileAuth(int id, String auths); + + /** + * 获取用户 + * + * @param permission 当前用户权限 + * @param condition 筛选条件 + * @param offset 偏移 + * + * @return {@link List} + */ + List<User> listUser(int permission, String condition, int offset); + + /** + * 登录 + * + * @param loginName 登录名 + * @param password 密码 + * @param token 自动登录 + * @param response 响应 + * + * @return {@link User} + */ + User login(String loginName, String password, String token, HttpServletResponse response); + + /** + * 注册 + * + * @param username 用户名 + * @param email 邮箱 + * @param password 密码 + * + * @return 是否插入成功 + */ + boolean register(String username, String email, String password); + + /** + * 重置密码 + * + * @param email 邮箱 + * @param password 密码 + * + * @return {@link Boolean} + */ + boolean resetPasswordByEmail(String email, String password); + + /** + * 检查用户名是否存在 + * + * @param username 用户名 + * + * @return {@link Boolean} + */ + boolean usernameExists(String username); + + /** + * 通过编号获取用户 + * + * @param id 编号 + * + * @return {@link User} + */ + User getUserById(int id); + + /** + * 更新用户登录时间 + * + * @param user {@link User} + */ + void updateUserLoginTime(User user); + + /** + * 更新密码 + * + * @param password 密码 + * @param id 用户编号 + * + * @return 是否更新成功 + */ + boolean updatePasswordById(String password, int id); + + /** + * 检查密码是否合法 + * + * @param password 密码 + * + * @return {@link Boolean} + */ + boolean checkPassword(String password); + + /** + * 检查邮箱是否存在 + * + * @param email 邮箱 + * + * @return {@link Boolean} + */ + boolean emailExists(String email); + + /** + * 更新用户基本信息 + * + * @param id 编号 + * @param avatar 头像 + * @param realName 真实姓名 + * @param email 邮箱 + * + * @return 是否更新成功 + */ + boolean updateBasicInfoById(int id, String avatar, String realName, String email); + + /** + * 用过用户名获取用户Id + * + * @param usernameOrEmail 用户名或邮箱 + * + * @return 用户编号 + */ + int getUserId(String usernameOrEmail); +} 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); + } +} |
