├── .gitignore ├── .travis.yml ├── README.md ├── preview ├── 1_myfile.png ├── 1_upload.png ├── 2_link.png ├── 2_myshare.png ├── 3_login.png └── 3_pubshare.png ├── server ├── README.md ├── doc │ ├── api_common.md │ ├── api_file.md │ └── api_user.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── pdwu │ │ │ └── easycloud │ │ │ ├── common │ │ │ ├── bean │ │ │ │ ├── ResultBean.java │ │ │ │ ├── ResultCode.java │ │ │ │ └── SessionAttributeConstant.java │ │ │ ├── config │ │ │ │ ├── AppConfig.java │ │ │ │ └── MyObjectMapper.java │ │ │ └── util │ │ │ │ ├── JsonUtils.java │ │ │ │ ├── MD5Utils.java │ │ │ │ ├── UuidUtils.java │ │ │ │ └── WebUtils.java │ │ │ ├── file │ │ │ ├── bean │ │ │ │ ├── FileInfoBean.java │ │ │ │ └── ShareInfoBean.java │ │ │ ├── constant │ │ │ │ ├── FileInfoConstant.java │ │ │ │ └── ShareInfoConstant.java │ │ │ ├── controller │ │ │ │ ├── DownloadController.java │ │ │ │ ├── FileManageController.java │ │ │ │ └── PublicShareController.java │ │ │ ├── dao │ │ │ │ ├── FileInfoDao.java │ │ │ │ ├── FileInfoDao.xml │ │ │ │ ├── ShareInfoDao.java │ │ │ │ └── ShareInfoDao.xml │ │ │ ├── service │ │ │ │ ├── IDownloadService.java │ │ │ │ ├── IFileService.java │ │ │ │ ├── IShareService.java │ │ │ │ ├── IShortLinkService.java │ │ │ │ └── impl │ │ │ │ │ ├── DownloadServiceImpl.java │ │ │ │ │ ├── FileServiceImpl.java │ │ │ │ │ ├── ShareServiceImpl.java │ │ │ │ │ └── ShortLinkServiceImpl.java │ │ │ └── util │ │ │ │ ├── FileSizeSerialize.java │ │ │ │ ├── FileSizeUtils.java │ │ │ │ └── FileUtils.java │ │ │ └── user │ │ │ ├── bean │ │ │ ├── TokenBean.java │ │ │ └── UserBean.java │ │ │ ├── constant │ │ │ └── TokenConstant.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── dao │ │ │ ├── TokenDao.java │ │ │ ├── TokenDao.xml │ │ │ ├── UserDao.java │ │ │ └── UserDao.xml │ │ │ ├── interceptor │ │ │ └── LoginInterceptor.java │ │ │ ├── service │ │ │ ├── ITokenService.java │ │ │ ├── IUserService.java │ │ │ └── impl │ │ │ │ ├── TokenServiceImpl.java │ │ │ │ └── UserServiceImpl.java │ │ │ └── util │ │ │ └── TokenUtils.java │ ├── resources │ │ ├── app │ │ │ └── easycloud.properties │ │ ├── db.properties │ │ ├── db │ │ │ ├── create_db.sql │ │ │ ├── create_table.sql │ │ │ └── h2 │ │ │ │ └── createTable.sql │ │ ├── log4j.properties │ │ ├── mybatis-config.xml │ │ └── spring │ │ │ ├── db-test.xml │ │ │ ├── spring-context.xml │ │ │ ├── spring-mvc.xml │ │ │ └── spring-mybatis.xml │ └── webapp │ │ ├── WEB-INF │ │ └── web.xml │ │ └── index.jsp │ └── test │ └── java │ └── com │ └── pdwu │ └── easycloud │ ├── common │ ├── bean │ │ └── BeanTest.java │ ├── config │ │ └── AppConfigTest.java │ └── util │ │ ├── JsonUtilsTest.java │ │ ├── MD5UtilsTest.java │ │ ├── UuidUtilsTest.java │ │ └── WebUtilsTest.java │ ├── file │ ├── controller │ │ ├── DownloadControllerTest.java │ │ ├── FileManageControllerTest.java │ │ └── PublicShareControllerTest.java │ ├── dao │ │ ├── FileInfoDaoTest.java │ │ └── ShareInfoDaoTest.java │ ├── service │ │ └── impl │ │ │ ├── DownloadServiceImplTest.java │ │ │ ├── FileServiceImplTest.java │ │ │ ├── ShareServiceImplTest.java │ │ │ └── ShortLinkServiceImplTest.java │ └── util │ │ ├── FileSizeUtilsTest.java │ │ └── FileUtilsTest.java │ └── user │ ├── controller │ └── UserControllerTest.java │ ├── dao │ ├── TokenDaoTest.java │ └── UserDaoTest.java │ ├── interceptor │ └── LoginInterceptorTest.java │ ├── service │ └── impl │ │ ├── TokenServiceImplTest.java │ │ └── UserServiceImplTest.java │ └── util │ └── TokenUtilsTest.java └── web ├── .babelrc ├── .editorconfig ├── .gitignore ├── .postcssrc.js ├── README.md ├── build ├── build.js ├── check-versions.js ├── logo.png ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js └── webpack.prod.conf.js ├── config ├── dev.env.js ├── index.js └── prod.env.js ├── index.html ├── package-lock.json ├── package.json ├── src ├── App.vue ├── components │ ├── AsideItem.vue │ ├── HeadItem.vue │ └── view │ │ ├── LoginView.vue │ │ ├── MyFileView.vue │ │ ├── MyShareView.vue │ │ ├── NotFound.vue │ │ ├── PubShareView.vue │ │ └── RegisterView.vue ├── main.js └── router │ └── index.js └── static └── .gitkeep /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | *.iml 3 | target/ 4 | 5 | .DS_Store 6 | web/node_modules/ 7 | web/dist/ 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | 12 | # Editor directories and files 13 | .idea 14 | .vscode 15 | *.suo 16 | *.ntvs* 17 | *.njsproj 18 | *.sln 19 | server/home/ 20 | server/.settings/ 21 | server/.classpath 22 | server/.project 23 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | sudo: false 3 | 4 | script: 5 | - cd ./server 6 | - mvn cobertura:cobertura 7 | 8 | after_success: 9 | - bash <(curl -s https://codecov.io/bash) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EasyCloud 2 | 3 | [![Build Status](https://travis-ci.org/pdwu/EasyCloud.svg?branch=master)](https://travis-ci.org/pdwu/EasyCloud) 4 | [![codecov](https://codecov.io/gh/pdwu/EasyCloud/branch/master/graph/badge.svg)](https://codecov.io/gh/pdwu/EasyCloud) 5 | 6 | ## 简介 7 | EasyCloud是一个前后端分离的简易文件云平台,支持上传和管理文件、图片在线预览和生成分享链接。 8 | 9 | ## 技术栈 10 | - 后端使用Spring, SpringMVC, Mybatis, MySQL实现,详见 [/server/README.md](./server/README.md) 11 | - 前端使用Vue.js, Element UI实现 12 | 13 | ## 预览 14 | 15 | - 登录注册 16 | ![](./preview/3_login.png) 17 | - 我的文件页面 18 | ![](./preview/1_myfile.png) 19 | - 上传文件 20 | ![](./preview/1_upload.png) 21 | - 我的分享页面 22 | ![](./preview/2_myshare.png) 23 | - 查看分享链接 24 | ![](./preview/2_link.png) 25 | - 访问链接 26 | ![](./preview/3_pubshare.png) 27 | 28 | 29 | --- 30 | 31 | ## 部署运行 32 | 33 | 以下示例两种运行方式。 34 | 35 | ### 开发环境运行 36 | - 后端 `/server` 37 | 1. `/src/resources/db.properties` 配置MySQL数据库连接信息 38 | 2. `/src/resoutces/app/easycloud.properties` 修改App配置(非必须) 39 | 3. 使用IDE导入项目并配置Tomcat运行 40 | 41 | - 前端 `/web` 42 | 1. `npm install` 43 | 2. 修改 `config/index.js` 中 `module.exports: dev.proxyTable.target` 为服务端地址 44 | 3. `npm run dev` 45 | 46 | ### 使用Nginx部署运行(生产环境) 47 | - 1.修改配置(同上) 48 | > 也可在 `/src/resoutces/spring/spring-mybatis.xml` 和 `src/main/java/com/pdwu/easycloud/common/config/AppConfig.java` 里面增加一条生产环境配置文件的路径 49 | 50 | - 2.打包 51 | - 后端执行 `mvn clean package` 生成war包 52 | - 前端执行 `npm run build` 在dist目录下生成静态文件 53 | 54 | - 3.服务器部署 55 | - 运行后端,如使用Tomcat在上下文运行: `localhost:8080/easycloud` 路径:`/var/lib/tomcat/webapps/easycloud` 56 | - 将前端 `/dist` 目录下的所有文件拷贝到任一路径,如:`/home/myApps/easycloud_web` 57 | 58 | - 4.Nginx配置 59 | 60 | - 后端配置 `/etc/nginx/conf.d/easycloud.conf` 61 | ``` 62 | server { 63 | listen 9001; 64 | server_name localhost; 65 | root /var/lib/tomcat/webapps/easycloud; 66 | 67 | location / { 68 | proxy_pass http://localhost:8080/easycloud/; 69 | } 70 | } 71 | ``` 72 | 73 | - 前端配置 `/etc/nginx/conf.d/easycloud_web.conf` 74 | ``` 75 | server { 76 | listen 80; 77 | server_name localhost; 78 | 79 | location / { 80 | root /home/myApps/easycloud_web; 81 | index index.html; 82 | try_files $uri $uri/ /index.html; 83 | } 84 | 85 | location /imgs { 86 | alias /home/myApps/easycloud_web/imgs; 87 | } 88 | 89 | location /api { 90 | proxy_pass http://localhost:8080/easycloud/api; 91 | } 92 | } 93 | ``` 94 | 95 | - 注:以上是服务端部署在Tomcat上下文下的演示,部署在根目录需要相应改变 -------------------------------------------------------------------------------- /preview/1_myfile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/preview/1_myfile.png -------------------------------------------------------------------------------- /preview/1_upload.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/preview/1_upload.png -------------------------------------------------------------------------------- /preview/2_link.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/preview/2_link.png -------------------------------------------------------------------------------- /preview/2_myshare.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/preview/2_myshare.png -------------------------------------------------------------------------------- /preview/3_login.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/preview/3_login.png -------------------------------------------------------------------------------- /preview/3_pubshare.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/preview/3_pubshare.png -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | # EasyCloud 2 | 3 | [![Build Status](https://travis-ci.org/pdwu/EasyCloud.svg?branch=master)](https://travis-ci.org/pdwu/EasyCloud) 4 | [![codecov](https://codecov.io/gh/pdwu/EasyCloud/branch/master/graph/badge.svg)](https://codecov.io/gh/pdwu/EasyCloud) 5 | 6 | ### 简介 7 | EasyCloud是一个简易的文件分享平台。 8 | 9 | ### 技术栈 10 | - Java, Maven 11 | - Spring, SpringMVC, Mybatis, MySQL 12 | - Unit Test: JUnit4, Mockito, DbSetup, H2Database 13 | - Travis自动构建 [EasyCloud - Travis CI](https://travis-ci.org/pdwu/EasyCloud) 14 | - Codecov测试覆盖率预览 [EasyCloud - Coverage](https://codecov.io/gh/pdwu/EasyCloud) 15 | 16 | 17 | ### 设计 18 | - 使用拦截器统一验证token 19 | - 分享服务中,短链接使用长整形转62进制的方式实现 20 | - 统一返回的数据格式 21 | 1. 成功则返回200和需要的数据 22 | ```json 23 | { 24 | "code":200, 25 | "data":{}, 26 | "msg":null 27 | } 28 | ``` 29 | 2. 失败则返回对应错误码和错误信息 30 | ```json 31 | { 32 | "code":400, 33 | "data":null, 34 | "msg":"参数错误" 35 | } 36 | ``` 37 | 38 | ### 接口概览 (已实现) 39 | - `~/api/pub/xxx` 公共接口 40 | - `~/api/usr/xxx` 用户登录才能访问,需要令牌 41 | 42 | | 模块 | 描述 | 请求路径 | 方法 | 令牌 | 备注 | 43 | |:----:|:------------------:|----------------------------|:----:|------|:------------------:| 44 | | 用户 | 登录 | /api/pub/login | POST | | | 45 | | | 注册 | /api/pub/register | POST | | | 46 | | | 注销 | /api/usr/logout | GET | 需要 | | 47 | | 文件 | 上传文件 | /api/usr/file/upload | POST | 需要 | | 48 | | | 获取用户的文件列表 | /api/usr/file/list | GET | 需要 | | 49 | | | 修改文件名 | /api/usr/file/rename | POST | 需要 | | 50 | | | 删除文件 | /api/usr/file/delete | POST | 需要 | | 51 | | | 分享文件 | /api/usr/file/share | POST | 需要 | | 52 | | | 取消分享 | /api/usr/file/cancelShare | POST | 需要 | | 53 | | | 获取个人分享列表 | /api/usr/file/shareList | GET | 需要 | | 54 | | 下载 | 下载文件 | /api/pub/download | GET | | 非公开文件需要令牌 | 55 | | | 预览文件 | /api/pub/preview | GET | | 非公开文件需要令牌 | 56 | | 分享 | 获取文件分享详情 | /api/pub/share/{shortlink} | GET | | | 57 | | | | | | | | 58 | 59 | ### 详细接口文档 60 | 文档路径: /doc/api_xxx.md 61 | - 通用规范 [api_common.md](./doc/api_common.md) 62 | - 文件模块 [api_file.md](./doc/api_file.md) 63 | - 用户模块 [api_user.md](./doc/api_user.md) 64 | 65 | -------------------------------------------------------------------------------- /server/doc/api_common.md: -------------------------------------------------------------------------------- 1 | ### 通用返回示例 2 | 3 | - 请求成功 4 | ``` 5 | 6 | { 7 | "code": 200, // 成功的返回码必定为200 8 | "data": "", // 返回的数据,不同接口不同 9 | "msg": null 10 | } 11 | ``` 12 | 13 | - 请求失败 14 | ``` 15 | 16 | { 17 | "code": 400, // 失败的返回码,400客户端错误,500服务端错误,其他请看对应接口 18 | "data": null, 19 | "msg": "参数错误" // 失败的提示语/原因 20 | } 21 | ``` 22 | 23 | ### 路径 24 | 25 | - ~/api/usr/xxx 代表该接口需要登录才能访问,必须带上token 26 | - ~/api/pub/xxx 公共接口,不登录也可以访问 27 | 28 | 29 | ### 其他 30 | - 登录成功后返回token以及用户信息 31 | - 可通过请求头部"Authorization"带上token 32 | - 或带上name=token的cookie (注:该cookie是HTTPOnly) 33 | 34 | 35 | -------------------------------------------------------------------------------- /server/doc/api_user.md: -------------------------------------------------------------------------------- 1 | #### 1.1 用户登录 2 | 3 | **请求地址** 4 | - ` ~/api/pub/login ` 5 | 6 | **请求方式** 7 | - POST JSON 8 | - 示例 9 | ``` 10 | { 11 | "account":"test", 12 | "password":"mypassword" 13 | } 14 | ``` 15 | 16 | **参数** 17 | 18 | |参数名|必选|类型|说明| 19 | |:---- |:---|:----- |----- | 20 | |account |是 |string |用户账户 | 21 | |password |是 |string |登录密码 | 22 | 23 | 24 | **返回示例** 25 | 26 | ``` json 27 | { 28 | "msg": "", 29 | "code": 200, 30 | "data": { 31 | "userId": 10026, 32 | "account": "test", 33 | "password": null, 34 | "createTime": "2018-01-06 02:20:07", 35 | "lastTime": "2018-01-06 02:20:07", 36 | "token": "3032506a6a774036a16d7cf0814f1a86" 37 | } 38 | } 39 | ``` 40 | 41 | **返回参数说明** 42 | 43 | |参数名|类型|说明| 44 | |:----- |:-----|----- | 45 | |userId|long|用户id| 46 | |account|string|用户账户| 47 | |createTime|string|创建时间| 48 | |lastTime|string|最后修改时间| 49 | |token|string|令牌| 50 | 51 | 52 | **备注** 53 | 54 | - none 55 | 56 | --- 57 | 58 | #### 1.2 用户注册 59 | 60 | **请求地址** 61 | - ` ~/api/pub/register ` 62 | 63 | **请求方式** 64 | - POST JSON 65 | - 示例 66 | ``` 67 | { 68 | "account":"test", 69 | "password":"mypassword" 70 | } 71 | ``` 72 | 73 | **参数** 74 | 75 | |参数名|必选|类型|说明| 76 | |:---- |:---|:----- |----- | 77 | |account |是 |string |用户账户 | 78 | |password |是 |string |登录密码 | 79 | 80 | 81 | **返回示例** 82 | 83 | ``` json 84 | { 85 | "code": 200, 86 | "data": "", 87 | "msg": null 88 | } 89 | ``` 90 | 91 | **返回参数说明** 92 | 93 | |参数名|类型|说明| 94 | |:----- |:-----|----- | 95 | 96 | **备注** 97 | 98 | - none 99 | 100 | --- 101 | 102 | #### 1.3 用户注销 103 | 104 | **请求地址** 105 | - ` ~/api/usr/logout ` 需要token 106 | 107 | **请求方式** 108 | - GET 109 | 110 | **参数** 111 | 112 | |参数名|必选|类型|说明| 113 | |:---- |:---|:----- |----- | 114 | 115 | 116 | **返回示例** 117 | 118 | ``` json 119 | { 120 | "code": 200, 121 | "data": "", 122 | "msg": null 123 | } 124 | ``` 125 | 126 | **返回参数说明** 127 | 128 | |参数名|类型|说明| 129 | |:----- |:-----|----- | 130 | 131 | **备注** 132 | 133 | - none 134 | 135 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/bean/ResultBean.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.bean; 2 | 3 | /** 4 | * Created by pdwu on 2017/11/22. 5 | */ 6 | public class ResultBean { 7 | private String msg; 8 | private int code; 9 | private Object data; 10 | 11 | //error 12 | public static final ResultBean ARG_ERROR = fail("参数异常"); 13 | public static final ResultBean SERVER_ERROR = fail(ResultCode.server_error, "服务器异常"); 14 | 15 | public ResultBean() { 16 | } 17 | 18 | public ResultBean(int code, Object data, String msg) { 19 | this.code = code; 20 | this.msg = msg; 21 | this.data = data; 22 | } 23 | 24 | 25 | public static ResultBean success(Object data) { 26 | return new ResultBean(ResultCode.ok, data, ""); 27 | } 28 | 29 | public static ResultBean fail(String errorMsg) { 30 | return new ResultBean(ResultCode.fail, null, errorMsg); 31 | } 32 | 33 | public static ResultBean fail(int resultCode, String errorMsg) { 34 | return new ResultBean(resultCode, null, errorMsg); 35 | } 36 | 37 | 38 | public String getMsg() { 39 | return msg; 40 | } 41 | 42 | 43 | public int getCode() { 44 | return code; 45 | } 46 | 47 | 48 | public Object getData() { 49 | return data; 50 | } 51 | 52 | 53 | @Override 54 | public String toString() { 55 | return "ResultBean{" + 56 | "msg='" + msg + '\'' + 57 | ", code=" + code + 58 | ", data=" + data + 59 | '}'; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/bean/ResultCode.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.bean; 2 | 3 | /** 4 | * Created by pdwu on 2017/12/9. 5 | */ 6 | public class ResultCode { 7 | public static final int ok = 200; 8 | public static final int fail = 400; 9 | public static final int server_error = 500; 10 | public static final int not_found = 404; 11 | public static final int unauthorized = 401; 12 | } 13 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/bean/SessionAttributeConstant.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.bean; 2 | 3 | /** 4 | * Created by pdwu on 2018/1/17. 5 | */ 6 | public class SessionAttributeConstant { 7 | 8 | public static final String TOKEN = "session_token"; 9 | 10 | public static final String USER_ID = "userId"; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.PropertySource; 6 | import org.springframework.context.annotation.PropertySources; 7 | import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | * Created by pdwu on 2017/12/19. 12 | */ 13 | @Component 14 | @PropertySource(value = {"classpath:app/easycloud.properties", "file:/home/myAppConf/easycloud.app.properties"}, ignoreResourceNotFound = true) 15 | public class AppConfig { 16 | 17 | //应用部署地址/域名 18 | @Value("${app.common.site}") 19 | public String appSite; 20 | 21 | //短链接前缀 eg: example.com/share/abcd 22 | public static final String URL_SHORT_LINK_PRE = "share/"; 23 | 24 | //用户上传文件的保存地址 25 | @Value("${app.file.userfilepath}") 26 | private String userFilePath; 27 | 28 | /** 29 | * api请求地址 30 | *

31 | * /api/pub/xxx 公共API 32 | * /api/usr/xxx 需要登录的API 33 | */ 34 | 35 | //用户模块 36 | public static final String API_LOGIN = "/api/pub/login"; 37 | public static final String API_LOGOUT = "/api/usr/logout"; 38 | public static final String API_REGISTER = "/api/pub/register"; 39 | 40 | //文件模块 41 | public static final String API_FILE = "/api/usr/file"; 42 | public static final String API_FILE_UPLOAD = API_FILE + "/upload"; 43 | public static final String API_FILE_LIST = API_FILE + "/list"; 44 | public static final String API_FILE_RENAME = API_FILE + "/rename"; 45 | public static final String API_FILE_DELETE = API_FILE + "/delete"; 46 | public static final String API_FILE_SHARE = API_FILE + "/share"; 47 | public static final String API_FILE_CANCEL_SHARE = API_FILE + "/cancelShare"; 48 | public static final String API_FILE_SHARE_LIST = API_FILE + "/shareList"; 49 | 50 | //下载 51 | public static final String API_PUB_DOWNLOAD = "/api/pub/download"; 52 | //预览 53 | public static final String API_PUB_PREVIEW = "/api/pub/preview"; 54 | 55 | //分享信息 56 | public static final String API_PUB_SHARE = "/api/pub/share"; 57 | 58 | public String getUserFilePath() { 59 | return userFilePath; 60 | } 61 | 62 | public void setUserFilePath(String userFilePath) { 63 | this.userFilePath = userFilePath; 64 | } 65 | 66 | public String getAppSite() { 67 | return appSite; 68 | } 69 | 70 | public void setAppSite(String appSite) { 71 | this.appSite = appSite; 72 | } 73 | 74 | //need this to resolve ${}, if use @PropertySource 75 | @Bean 76 | public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 77 | PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); 78 | configurer.setIgnoreUnresolvablePlaceholders(true); 79 | return configurer; 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/config/MyObjectMapper.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.SerializationFeature; 5 | 6 | public class MyObjectMapper extends ObjectMapper { 7 | 8 | public MyObjectMapper(){ 9 | this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/util/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.pdwu.easycloud.common.bean.ResultBean; 6 | import com.pdwu.easycloud.common.config.MyObjectMapper; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * Created by pdwu on 2017/12/14. 12 | */ 13 | public class JsonUtils { 14 | 15 | private static ObjectMapper objectMapper = new MyObjectMapper(); 16 | 17 | public static String objectToJson(Object obj) throws JsonProcessingException { 18 | 19 | String res; 20 | res = objectMapper.writeValueAsString(obj); 21 | 22 | return res; 23 | 24 | } 25 | 26 | public static ResultBean jsonToResultBean(String string) throws IOException { 27 | return objectMapper.readValue(string, ResultBean.class); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/util/MD5Utils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import org.springframework.util.DigestUtils; 4 | 5 | /** 6 | * Created by pdwu on 2018/1/16. 7 | */ 8 | public class MD5Utils { 9 | 10 | public static String getStringMd5(String str) { 11 | 12 | //md5摘要(小写) 13 | String res = DigestUtils.md5DigestAsHex(str.getBytes()); 14 | 15 | return res; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/util/UuidUtils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import java.util.UUID; 4 | 5 | public class UuidUtils { 6 | 7 | public static String newUUID() { 8 | String uuid = UUID.randomUUID().toString(); 9 | char[] chars = new char[32]; 10 | for (int i = 0, j = 0; i < uuid.length(); i++) { 11 | if (uuid.charAt(i) != '-') { 12 | chars[j++] = uuid.charAt(i); 13 | } 14 | } 15 | return new String(chars); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/common/util/WebUtils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import org.apache.commons.lang3.StringUtils; 4 | 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | /** 10 | * Created by pdwu on 2017/12/14. 11 | */ 12 | public class WebUtils { 13 | 14 | private static String[] pubUris = new String[]{ 15 | "/easycloud/api/pub.*", 16 | "/api/pub.*", 17 | "/error.*", 18 | "/static.*" 19 | }; 20 | 21 | public static boolean checkUriPublic(String uri) { 22 | 23 | if (StringUtils.isBlank(uri)) { 24 | return false; 25 | } 26 | 27 | for (String s : pubUris) { 28 | if (uri.matches(s)) { 29 | return true; 30 | } 31 | } 32 | 33 | return false; 34 | } 35 | 36 | public static Map generateListResultMap(List list, int totalNumber, int pageSize, int pageNum){ 37 | 38 | Map map = new HashMap(); 39 | map.put("list", list); 40 | map.put("count", list.size()); 41 | map.put("pageNum", pageNum); 42 | map.put("pageSize", pageSize); 43 | 44 | map.put("totalNumber", totalNumber); 45 | 46 | int totalPage = totalNumber / pageSize; 47 | if (totalNumber % pageSize > 0) { 48 | totalPage++; 49 | } 50 | map.put("totalPage", totalPage); 51 | 52 | return map; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/bean/FileInfoBean.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.bean; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 6 | import com.pdwu.easycloud.file.util.FileSizeSerialize; 7 | 8 | import java.util.Date; 9 | 10 | /** 11 | * Created by pdwu on 2017/12/18. 12 | */ 13 | @JsonIgnoreProperties(value = {"truePath"}) 14 | public class FileInfoBean { 15 | 16 | private Long fileId; 17 | private Long userId; 18 | private String md5; 19 | private String truePath; //服务器保存文件的真实路径 20 | private String name; 21 | private Integer status; 22 | 23 | @JsonSerialize(using = FileSizeSerialize.class) 24 | private Long size; 25 | 26 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 27 | private Date createTime; 28 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 29 | private Date lastTime; 30 | 31 | public Long getSize() { 32 | return size; 33 | } 34 | 35 | public void setSize(Long size) { 36 | this.size = size; 37 | } 38 | 39 | public Long getFileId() { 40 | return fileId; 41 | } 42 | 43 | public void setFileId(Long fileId) { 44 | this.fileId = fileId; 45 | } 46 | 47 | public Long getUserId() { 48 | return userId; 49 | } 50 | 51 | public void setUserId(Long userId) { 52 | this.userId = userId; 53 | } 54 | 55 | public String getMd5() { 56 | return md5; 57 | } 58 | 59 | public void setMd5(String md5) { 60 | this.md5 = md5; 61 | } 62 | 63 | public String getTruePath() { 64 | return truePath; 65 | } 66 | 67 | public void setTruePath(String truePath) { 68 | this.truePath = truePath; 69 | } 70 | 71 | public String getName() { 72 | return name; 73 | } 74 | 75 | public void setName(String name) { 76 | this.name = name; 77 | } 78 | 79 | public Integer getStatus() { 80 | return status; 81 | } 82 | 83 | public void setStatus(Integer status) { 84 | this.status = status; 85 | } 86 | 87 | public Date getCreateTime() { 88 | return createTime; 89 | } 90 | 91 | public void setCreateTime(Date createTime) { 92 | this.createTime = createTime; 93 | } 94 | 95 | public Date getLastTime() { 96 | return lastTime; 97 | } 98 | 99 | public void setLastTime(Date lastTime) { 100 | this.lastTime = lastTime; 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "FileInfoBean{" + 106 | "fileId=" + fileId + 107 | ", userId=" + userId + 108 | ", md5='" + md5 + '\'' + 109 | ", truePath='" + truePath + '\'' + 110 | ", name='" + name + '\'' + 111 | ", status=" + status + 112 | ", createTime=" + createTime + 113 | ", lastTime=" + lastTime + 114 | '}'; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/bean/ShareInfoBean.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.bean; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * Created by pdwu on 2017/12/18. 9 | */ 10 | public class ShareInfoBean { 11 | 12 | private Long shareId; 13 | private Long userId; 14 | private Long fileId; 15 | private String password; 16 | private String shortlink; 17 | private Integer status; 18 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 19 | private Date createTime; 20 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 21 | private Date lastTime; 22 | private FileInfoBean fileInfo; 23 | 24 | public String getPassword() { 25 | return password; 26 | } 27 | 28 | public void setPassword(String password) { 29 | this.password = password; 30 | } 31 | 32 | public String getShortlink() { 33 | return shortlink; 34 | } 35 | 36 | public void setShortlink(String shortlink) { 37 | this.shortlink = shortlink; 38 | } 39 | 40 | public FileInfoBean getFileInfo() { 41 | return fileInfo; 42 | } 43 | 44 | public void setFileInfo(FileInfoBean fileInfo) { 45 | this.fileInfo = fileInfo; 46 | } 47 | 48 | public Long getShareId() { 49 | return shareId; 50 | } 51 | 52 | public void setShareId(Long shareId) { 53 | this.shareId = shareId; 54 | } 55 | 56 | public Long getUserId() { 57 | return userId; 58 | } 59 | 60 | public void setUserId(Long userId) { 61 | this.userId = userId; 62 | } 63 | 64 | public Long getFileId() { 65 | return fileId; 66 | } 67 | 68 | public void setFileId(Long fileId) { 69 | this.fileId = fileId; 70 | } 71 | 72 | public Integer getStatus() { 73 | return status; 74 | } 75 | 76 | public void setStatus(Integer status) { 77 | this.status = status; 78 | } 79 | 80 | public Date getCreateTime() { 81 | return createTime; 82 | } 83 | 84 | public void setCreateTime(Date createTime) { 85 | this.createTime = createTime; 86 | } 87 | 88 | public Date getLastTime() { 89 | return lastTime; 90 | } 91 | 92 | public void setLastTime(Date lastTime) { 93 | this.lastTime = lastTime; 94 | } 95 | 96 | @Override 97 | public String toString() { 98 | return "ShareInfoBean{" + 99 | "shareId=" + shareId + 100 | ", userId=" + userId + 101 | ", fileId=" + fileId + 102 | ", password='" + password + '\'' + 103 | ", shortlink='" + shortlink + '\'' + 104 | ", status=" + status + 105 | ", createTime=" + createTime + 106 | ", lastTime=" + lastTime + 107 | ", fileInfo=" + fileInfo + 108 | '}'; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/constant/FileInfoConstant.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.constant; 2 | 3 | /** 4 | * Created by pdwu on 2017/12/18. 5 | */ 6 | public class FileInfoConstant { 7 | 8 | //文件状态: 正常 9 | public static final int STATUS_NORMAL = 0; 10 | 11 | //文件状态: 已删除 12 | public static final int STATUS_DELETE = 1; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/constant/ShareInfoConstant.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.constant; 2 | 3 | /** 4 | * Created by pdwu on 2017/12/18. 5 | */ 6 | public class ShareInfoConstant { 7 | 8 | //分享状态: 正常 9 | public static final int STATUS_NORMAL = 1; 10 | 11 | //分享状态: 取消分享 12 | public static final int STATUS_CANCLE = 0; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/controller/DownloadController.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.controller; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.ResultCode; 5 | import com.pdwu.easycloud.common.config.AppConfig; 6 | import com.pdwu.easycloud.common.util.JsonUtils; 7 | import com.pdwu.easycloud.file.bean.FileInfoBean; 8 | import com.pdwu.easycloud.file.service.IDownloadService; 9 | import org.apache.commons.lang3.StringUtils; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Controller; 12 | import org.springframework.util.FileCopyUtils; 13 | import org.springframework.util.MimeTypeUtils; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | 16 | import javax.servlet.http.HttpServletRequest; 17 | import javax.servlet.http.HttpServletResponse; 18 | import java.io.*; 19 | import java.net.URLConnection; 20 | import java.util.Map; 21 | 22 | /** 23 | * Created by pdwu on 2017/12/21. 24 | */ 25 | @Controller 26 | public class DownloadController { 27 | 28 | @Autowired 29 | private IDownloadService downloadService; 30 | 31 | @RequestMapping(value = AppConfig.API_PUB_DOWNLOAD) 32 | public void download(HttpServletRequest request, HttpServletResponse response) throws IOException { 33 | 34 | Long userId = (Long) request.getSession().getAttribute("userId"); 35 | 36 | String fileIdStr = request.getParameter("fileId"); 37 | String shareIdStr = request.getParameter("shareId"); 38 | 39 | Long fileId = null; 40 | Long shareId = null; 41 | 42 | if (!StringUtils.isBlank(fileIdStr)) { 43 | fileId = Long.valueOf(fileIdStr); 44 | } 45 | 46 | if (!StringUtils.isBlank(shareIdStr)) { 47 | shareId = Long.valueOf(shareIdStr); 48 | } 49 | 50 | ResultBean bean = downloadService.download(userId, fileId, shareId, null); 51 | if (bean.getCode() != ResultCode.ok) { 52 | writeError(response, bean); 53 | } else { 54 | Map map = (Map) bean.getData(); 55 | writeFile(response, (File) map.get("file"), (FileInfoBean) map.get("fileInfo"), true); 56 | } 57 | 58 | } 59 | 60 | private void writeError(HttpServletResponse response, ResultBean resultBean) throws IOException { 61 | 62 | response.setStatus(resultBean.getCode()); 63 | 64 | String json = JsonUtils.objectToJson(resultBean); 65 | response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE); 66 | response.setCharacterEncoding("UTF-8"); 67 | response.getWriter().write(json); 68 | 69 | } 70 | 71 | private void writeFile(HttpServletResponse response, File file, FileInfoBean fileInfoBean, boolean needDisposition) throws IOException { 72 | if (file == null || fileInfoBean == null || !file.exists()) { 73 | writeError(response, ResultBean.SERVER_ERROR); 74 | return; 75 | } 76 | 77 | String mimeType = URLConnection.guessContentTypeFromName(fileInfoBean.getName()); 78 | if (mimeType == null) { 79 | mimeType = "application/octet-stream"; 80 | } 81 | 82 | //防止中文乱码 83 | String fileName = new String(fileInfoBean.getName().getBytes("gbk"), "ISO8859-1"); 84 | 85 | response.setContentType(mimeType); 86 | //response.setContentLengthLong(file.length()); 87 | if (needDisposition) { 88 | response.setHeader("Content-Disposition", "attachment;fileName=\"" + fileName + "\""); 89 | } 90 | 91 | //文件下载 92 | InputStream in = new BufferedInputStream(new FileInputStream(file)); 93 | FileCopyUtils.copy(in, response.getOutputStream()); 94 | } 95 | 96 | @RequestMapping(value = {AppConfig.API_PUB_PREVIEW}) 97 | public void preview(HttpServletRequest request, HttpServletResponse response, Long fileId, Long shareId) throws IOException { 98 | 99 | Long userId = (Long) request.getSession().getAttribute("userId"); 100 | 101 | ResultBean bean = downloadService.download(userId, fileId, shareId, null); 102 | if (bean.getCode() != ResultCode.ok) { 103 | writeError(response, bean); 104 | } else { 105 | Map map = (Map) bean.getData(); 106 | writeFile(response, (File) map.get("file"), (FileInfoBean) map.get("fileInfo"), false); 107 | } 108 | 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/controller/FileManageController.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.controller; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.ResultCode; 5 | import com.pdwu.easycloud.common.config.AppConfig; 6 | import com.pdwu.easycloud.common.util.WebUtils; 7 | import com.pdwu.easycloud.file.bean.FileInfoBean; 8 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 9 | import com.pdwu.easycloud.file.constant.FileInfoConstant; 10 | import com.pdwu.easycloud.file.service.IFileService; 11 | import com.pdwu.easycloud.file.service.IShareService; 12 | import org.apache.commons.io.FileUtils; 13 | import org.apache.commons.lang3.StringUtils; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.web.bind.annotation.*; 19 | import org.springframework.web.multipart.MultipartFile; 20 | 21 | import javax.servlet.http.HttpServletRequest; 22 | import javax.servlet.http.HttpServletResponse; 23 | import java.util.HashMap; 24 | import java.util.List; 25 | import java.util.Map; 26 | 27 | /** 28 | * Created by pdwu on 2017/12/19. 29 | */ 30 | @Controller 31 | public class FileManageController { 32 | 33 | private final Logger log = LoggerFactory.getLogger(getClass()); 34 | 35 | @Autowired 36 | private IFileService fileService; 37 | 38 | @Autowired 39 | private IShareService shareService; 40 | 41 | @RequestMapping(value = AppConfig.API_FILE_UPLOAD, method = RequestMethod.POST) 42 | @ResponseBody 43 | public Object uploadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file) { 44 | 45 | //前端需要设置name=file 46 | 47 | if (file == null) { 48 | response.setStatus(ResultCode.fail); 49 | return ResultBean.ARG_ERROR; 50 | } 51 | 52 | Long userId = (Long) request.getSession().getAttribute("userId"); 53 | 54 | log.debug("uploadFile userId: {}, multipartFile contentType: {}, Name: {}, OriginalFilename: {}, size: {}", userId, 55 | file.getContentType(), file.getName(), file.getOriginalFilename(), file.getSize()); 56 | 57 | ResultBean resultBean = null; 58 | try { 59 | resultBean = fileService.uploadFile(userId, file); 60 | } catch (Exception e) { 61 | resultBean = ResultBean.SERVER_ERROR; 62 | } 63 | 64 | if (resultBean.getCode() != ResultCode.ok) { 65 | response.setStatus(ResultCode.server_error); 66 | } 67 | 68 | return resultBean; 69 | } 70 | 71 | @RequestMapping(value = AppConfig.API_FILE_LIST) 72 | @ResponseBody 73 | public Object listMyFiles(HttpServletRequest request, Integer pageNum, Integer pageSize) { 74 | 75 | Long userId = (Long) request.getSession().getAttribute("userId"); 76 | 77 | int intPageNum = 1; 78 | int intPageSize = 10; 79 | if (pageNum != null) { 80 | intPageNum = pageNum; 81 | } 82 | if (pageSize != null) { 83 | intPageSize = pageSize; 84 | } 85 | 86 | //获取列表详情 87 | List list = fileService.listUserFiles(userId, FileInfoConstant.STATUS_NORMAL, intPageNum, intPageSize); 88 | //获取总数 89 | int totalNumber = fileService.countUserFiles(userId, FileInfoConstant.STATUS_NORMAL); 90 | 91 | Map map = WebUtils.generateListResultMap(list, totalNumber, intPageSize, intPageNum); 92 | map.put("userId", userId); 93 | 94 | return ResultBean.success(map); 95 | } 96 | 97 | @RequestMapping(value = AppConfig.API_FILE_RENAME, method = RequestMethod.POST) 98 | @ResponseBody 99 | public Object rename(HttpServletRequest request, @RequestParam Long fileId, @RequestParam String filename) { 100 | //TODO 限制文件名长度 101 | return fileService.updateFileName(fileId, filename); 102 | 103 | } 104 | 105 | @RequestMapping(value = AppConfig.API_FILE_DELETE, method = RequestMethod.POST) 106 | @ResponseBody 107 | public Object delete(HttpServletRequest request, @RequestParam Long fileId) { 108 | 109 | return fileService.deleteFileInfo(fileId); 110 | 111 | } 112 | 113 | @RequestMapping(value = AppConfig.API_FILE_SHARE, method = RequestMethod.POST) 114 | @ResponseBody 115 | public Object share(HttpServletRequest request, @RequestParam Long fileId) { 116 | 117 | Long userId = (Long) request.getSession().getAttribute("userId"); 118 | 119 | return shareService.insertShareInfo(userId, fileId); 120 | } 121 | 122 | @RequestMapping(value = AppConfig.API_FILE_CANCEL_SHARE, method = RequestMethod.POST) 123 | @ResponseBody 124 | public Object cancelShare(HttpServletRequest request, @RequestParam Long shareId) { 125 | 126 | return shareService.deleteShareInfo(shareId); 127 | } 128 | 129 | @RequestMapping(value = AppConfig.API_FILE_SHARE_LIST) 130 | @ResponseBody 131 | public Object shareList(HttpServletRequest request, Integer status, Integer pageNum, Integer pageSize) { 132 | 133 | Long userId = (Long) request.getSession().getAttribute("userId"); 134 | 135 | int intPageNum = 1; 136 | if (pageNum != null) { 137 | intPageNum = pageNum; 138 | } 139 | 140 | int intPageSize = 10; 141 | if (pageSize != null) { 142 | intPageSize = pageSize; 143 | } 144 | 145 | List list = shareService.listUserShareInfos(userId, status, intPageNum, intPageSize); 146 | int totalNumber = shareService.countShareList(userId, status); 147 | 148 | Map map = WebUtils.generateListResultMap(list, totalNumber, intPageSize, intPageNum); 149 | 150 | return ResultBean.success(map); 151 | } 152 | 153 | } 154 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/controller/PublicShareController.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.controller; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.ResultCode; 5 | import com.pdwu.easycloud.common.config.AppConfig; 6 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 7 | import com.pdwu.easycloud.file.service.IShareService; 8 | import com.pdwu.easycloud.file.service.IShortLinkService; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | 17 | /** 18 | * Created by pdwu on 2017/12/20. 19 | */ 20 | @Controller 21 | @RequestMapping(value = AppConfig.API_PUB_SHARE) 22 | public class PublicShareController { 23 | 24 | @Autowired 25 | private IShareService shareService; 26 | 27 | @Autowired 28 | private IShortLinkService shortLinkService; 29 | 30 | @RequestMapping(value = "/{shareLink}") 31 | @ResponseBody 32 | public Object getShareFile(HttpServletRequest request, @PathVariable String shareLink) { 33 | 34 | Long shareId = shortLinkService.getShareId(shareLink); 35 | ShareInfoBean shareInfoBean = shareService.getShareFileInfoById(shareId); 36 | if (shareInfoBean == null) { 37 | return ResultBean.fail(ResultCode.not_found, "资源不存在"); 38 | } 39 | return ResultBean.success(shareInfoBean); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/dao/FileInfoDao.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.dao; 2 | 3 | import com.pdwu.easycloud.file.bean.FileInfoBean; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by pdwu on 2017/12/18. 10 | */ 11 | public interface FileInfoDao { 12 | 13 | /** 14 | * 新增一个文件信息 15 | * 16 | * @param param 17 | * @return 18 | */ 19 | int insertFileInfo(FileInfoBean param); 20 | 21 | /** 22 | * 获取文件信息列表 23 | * 24 | * @param param O(userId, fileId, md5, status, pageIndex & pageCount) 25 | * @return 26 | */ 27 | List selectFileInfoList(Map param); 28 | 29 | /** 30 | * 根据fileId更新文件名/状态 31 | * 32 | * @param param O(name, status), R(fileId, lastTime) 33 | * @return 34 | */ 35 | int updateFileInfo(Map param); 36 | 37 | /** 38 | * 统计文件信息数量 39 | * 40 | * @param param O(userId, status) 41 | * @return 42 | */ 43 | int countFileList(Map param); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/dao/FileInfoDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 21 | 22 | INSERT INTO file_info (user_id, md5, path, name, size, status, create_time, last_time) 23 | VALUES (#{userId}, #{md5}, #{truePath}, #{name}, #{size}, #{status}, #{createTime}, #{lastTime}) 24 | 25 | 26 | 27 | 56 | 57 | 58 | 59 | UPDATE file_info 60 | 61 | last_time = #{lastTime} 62 | 63 | 64 | , name = #{name} 65 | 66 | 67 | 68 | , status = #{status} 69 | 70 | 71 | 72 | 73 | 74 | 75 | file_id = #{fileId} 76 | 77 | 78 | 79 | 80 | 81 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/dao/ShareInfoDao.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.dao; 2 | 3 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by pdwu on 2017/12/18. 10 | */ 11 | public interface ShareInfoDao { 12 | 13 | /** 14 | * 新增一个文件分享信息 15 | * 16 | * @param bean 17 | * @return 18 | */ 19 | int insertShareInfo(ShareInfoBean bean); 20 | 21 | /** 22 | * 根据 shareId 更新分享状态 23 | * 24 | * @param param R(shareId, status, lastTime) 25 | * @return 26 | */ 27 | int updateShareInfoStatus(Map param); 28 | 29 | /** 30 | * 根据 shareId 更新分享信息 31 | * 32 | * @param param R(shareId, lastTime),O(shortlink) 33 | * @return 34 | */ 35 | int updateShareInfo(Map param); 36 | 37 | /** 38 | * 查找指定用户的分享信息/某条分享的详情 39 | * 40 | * @param param O(userId, shareId, status, fileId) 41 | * @return 42 | */ 43 | List selectShareInfo(Map param); 44 | 45 | /** 46 | * 删除分享 47 | * 48 | * @param param O(shareId, fileId) 49 | * @return 50 | */ 51 | int delete(Map param); 52 | 53 | /** 54 | * 统计分享数量 55 | * 56 | * @param param 57 | * @return 58 | */ 59 | int countShareList(Map param); 60 | 61 | } 62 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/dao/ShareInfoDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | 19 | 20 | 22 | 23 | INSERT INTO share_info (user_id, file_id, status, create_time, last_time) 24 | VALUES (#{userId}, #{fileId}, #{status}, #{createTime}, #{lastTime}) 25 | 26 | 27 | 28 | 74 | 75 | 76 | 77 | UPDATE share_info 78 | SET last_time = #{lastTime}, status = #{status} 79 | 80 | 81 | share_id = #{shareId} 82 | 83 | 84 | 85 | 86 | 87 | 88 | UPDATE share_info 89 | 90 | last_time = #{lastTime} 91 | 92 | 93 | , shortlink = #{shortlink} 94 | 95 | 96 | 97 | 98 | 99 | share_id = #{shareId} 100 | 101 | 102 | 103 | 104 | 105 | 106 | DELETE FROM share_info 107 | 108 | 109 | 110 | 111 | share_id = #{shareId} 112 | 113 | 114 | 115 | AND file_id = #{fileId} 116 | 117 | 118 | 119 | 120 | 121 | 122 | 139 | 140 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/IDownloadService.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | 5 | import java.util.Map; 6 | 7 | /** 8 | * Created by pdwu on 2017/12/21. 9 | */ 10 | public interface IDownloadService { 11 | /** 12 | * 下载文件 13 | * 14 | * @param userId 15 | * @param fileId 16 | * @param shareId 17 | * @param param 预留 18 | * @return 成功则取data转Map, key: fileInfo, file; value: FileInfoBean, File 19 | */ 20 | ResultBean download(Long userId, Long fileId, Long shareId, Map param); 21 | } 22 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/IFileService.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.file.bean.FileInfoBean; 5 | import org.springframework.web.multipart.MultipartFile; 6 | 7 | import java.util.Date; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * Created by pdwu on 2017/12/19. 13 | */ 14 | public interface IFileService { 15 | 16 | /** 17 | * 新增一份文件信息 18 | * 19 | * @param bean 20 | * @return 21 | */ 22 | ResultBean insertFileInfo(FileInfoBean bean); 23 | 24 | /** 25 | * 修改文件名 26 | * 27 | * @param fileId 28 | * @param fileName 29 | * @return 30 | */ 31 | ResultBean updateFileName(Long fileId, String fileName); 32 | 33 | /** 34 | * 删除文件信息(逻辑删除) 35 | * 36 | * @param fileId 37 | * @return 38 | */ 39 | ResultBean deleteFileInfo(Long fileId); 40 | 41 | 42 | /** 43 | * 查找用户的文件列表 44 | * 45 | * @param userId 46 | * @param status 为null代表所有状态 (FileInfoConstant.STATUS_xxx) 47 | * @return 48 | */ 49 | List listUserFiles(Long userId, Integer status, int pageNum, int pageSize); 50 | 51 | /** 52 | * 上传文件 53 | * 54 | * @param userId 55 | * @param file 56 | * @return 57 | * @throws Exception 58 | */ 59 | ResultBean uploadFile(Long userId, MultipartFile file) throws Exception; 60 | 61 | /** 62 | * 根据MD5查找是否已存在文件信息 63 | * 64 | * @param md5 65 | * @return 66 | */ 67 | FileInfoBean getFileInfoByMD5(String md5); 68 | 69 | /** 70 | * 根据fileId查找文件信息 71 | * 72 | * @param fileId 73 | * @return 74 | */ 75 | FileInfoBean getFileInfoById(Long fileId); 76 | 77 | /** 78 | * 获取用户文件列表的总数 79 | * 80 | * @param userId 81 | * @param status 为null代表所有状态 (FileInfoConstant.STATUS_xxx) 82 | * @return 83 | */ 84 | int countUserFiles(Long userId, Integer status); 85 | 86 | } 87 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/IShareService.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Created by pdwu on 2017/12/19. 10 | */ 11 | public interface IShareService { 12 | /** 13 | * 新增一个文件分享信息 (分享文件) 14 | * 15 | * @param userId 16 | * @param fileId 17 | * @return 18 | */ 19 | ResultBean insertShareInfo(Long userId, Long fileId); 20 | 21 | /** 22 | * 删除分享信息(取消分享) (物理删除) 23 | * 24 | * @param shareId 25 | * @return 26 | */ 27 | ResultBean deleteShareInfo(Long shareId); 28 | 29 | /** 30 | * 删除指定文件的分享 (物理删除) 31 | * 32 | * @param fileId 33 | * @return 34 | */ 35 | ResultBean deleteShareInfoByFileId(Long fileId); 36 | 37 | /** 38 | * 根据shareId查看分享的文件 39 | * 40 | * @param shareId 41 | * @return 42 | */ 43 | ShareInfoBean getShareFileInfoById(Long shareId); 44 | 45 | /** 46 | * 查找指定用户的分享列表 47 | * 48 | * @param userId 49 | * @param status 为null代表所有状态 50 | * @return 51 | */ 52 | List listUserShareInfos(Long userId, Integer status, int pageNum, int pageSize); 53 | 54 | /** 55 | * 统计用户分享列表数量 56 | * 57 | * @param userId 58 | * @param status 59 | * @return 60 | */ 61 | int countShareList(Long userId, Integer status); 62 | 63 | } 64 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/IShortLinkService.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service; 2 | 3 | /** 4 | * Created by pdwu on 2017/12/20. 5 | */ 6 | public interface IShortLinkService { 7 | 8 | /** 9 | * 根据shareId获取短链接 10 | * 11 | * @param shareId 12 | * @return 13 | */ 14 | String getShortLink(Long shareId); 15 | 16 | /** 17 | * 根据短链接获取shareId 18 | * 19 | * @param shortLink 20 | * @return 21 | */ 22 | Long getShareId(String shortLink); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/impl/DownloadServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service.impl; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.ResultCode; 5 | import com.pdwu.easycloud.file.bean.FileInfoBean; 6 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 7 | import com.pdwu.easycloud.file.constant.ShareInfoConstant; 8 | import com.pdwu.easycloud.file.service.IDownloadService; 9 | import com.pdwu.easycloud.file.service.IFileService; 10 | import com.pdwu.easycloud.file.service.IShareService; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.transaction.annotation.Transactional; 14 | 15 | import java.io.File; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | /** 20 | * Created by pdwu on 2017/12/21. 21 | */ 22 | @Service 23 | public class DownloadServiceImpl implements IDownloadService { 24 | 25 | @Autowired 26 | private IFileService fileService; 27 | 28 | @Autowired 29 | private IShareService shareService; 30 | 31 | @Transactional(readOnly = true) 32 | public ResultBean download(Long userId, Long fileId, Long shareId, Map param) { 33 | 34 | FileInfoBean fileInfoBean = fileService.getFileInfoById(fileId); 35 | 36 | if (fileInfoBean == null) { 37 | return ResultBean.fail(ResultCode.not_found, "文件不存在"); 38 | } 39 | 40 | //用户自己的文件 41 | if (userId != null && userId.equals(fileInfoBean.getUserId())) { 42 | //直接下载 43 | return getDownloadResult(fileInfoBean); 44 | } 45 | 46 | //不是用户自己的文件,那么理应带有shareId 47 | ShareInfoBean shareInfoBean = shareService.getShareFileInfoById(shareId); 48 | if (shareInfoBean == null) { 49 | return ResultBean.fail(ResultCode.not_found, "文件不存在或已取消分享"); 50 | } 51 | 52 | //确实存在该分享,再次判断是否有效 53 | if (shareInfoBean.getStatus() != ShareInfoConstant.STATUS_NORMAL) { 54 | return ResultBean.fail(ResultCode.not_found, "下载失败,文件不存在或已取消分享"); 55 | } 56 | 57 | return getDownloadResult(fileInfoBean); 58 | } 59 | 60 | private ResultBean getDownloadResult(FileInfoBean fileInfoBean) { 61 | File file = new File(fileInfoBean.getTruePath()); 62 | 63 | Map map = new HashMap(); 64 | map.put("fileInfo", fileInfoBean); 65 | map.put("file", file); 66 | return ResultBean.success(map); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/impl/ShareServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service.impl; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.config.AppConfig; 5 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 6 | import com.pdwu.easycloud.file.constant.ShareInfoConstant; 7 | import com.pdwu.easycloud.file.dao.ShareInfoDao; 8 | import com.pdwu.easycloud.file.service.IShareService; 9 | import com.pdwu.easycloud.file.service.IShortLinkService; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.transaction.annotation.Transactional; 14 | 15 | import java.util.*; 16 | 17 | /** 18 | * Created by pdwu on 2017/12/19. 19 | */ 20 | @Service 21 | public class ShareServiceImpl implements IShareService { 22 | 23 | 24 | @Autowired 25 | private ShareInfoDao shareInfoDao; 26 | 27 | @Autowired 28 | private IShortLinkService shortLinkService; 29 | 30 | @Autowired 31 | private AppConfig appConfig; 32 | 33 | @Transactional 34 | public ResultBean insertShareInfo(Long userId, Long fileId) { 35 | if (userId == null || fileId == null) { 36 | return ResultBean.ARG_ERROR; 37 | } 38 | 39 | ShareInfoBean bean = new ShareInfoBean(); 40 | bean.setUserId(userId); 41 | bean.setFileId(fileId); 42 | bean.setStatus(ShareInfoConstant.STATUS_NORMAL); 43 | 44 | Date now = new Date(); 45 | bean.setCreateTime(now); 46 | bean.setLastTime(now); 47 | 48 | shareInfoDao.insertShareInfo(bean); 49 | //短链接: (地址+分享目录前缀+短链接码) 50 | String shortlink = appConfig.getAppSite() + 51 | AppConfig.URL_SHORT_LINK_PRE + 52 | shortLinkService.getShortLink(bean.getShareId()); 53 | 54 | Map param = new HashMap(); 55 | param.put("shareId", bean.getShareId()); 56 | param.put("shortlink", shortlink); 57 | param.put("lastTime", new Date()); 58 | shareInfoDao.updateShareInfo(param); 59 | 60 | return ResultBean.success(bean); 61 | } 62 | 63 | @Transactional 64 | public ResultBean deleteShareInfo(Long shareId) { 65 | if (shareId == null) { 66 | return ResultBean.ARG_ERROR; 67 | } 68 | Map param = new HashMap(); 69 | 70 | param.put("shareId", shareId); 71 | int updated = shareInfoDao.delete(param); 72 | 73 | return updated >= 1 ? ResultBean.success("") : ResultBean.fail("不存在该分享"); 74 | } 75 | 76 | @Transactional 77 | public ResultBean deleteShareInfoByFileId(Long fileId) { 78 | if (fileId == null) { 79 | return ResultBean.ARG_ERROR; 80 | } 81 | Map param = new HashMap(); 82 | 83 | param.put("fileId", fileId); 84 | int updated = shareInfoDao.delete(param); 85 | 86 | return updated >= 1 ? ResultBean.success("") : ResultBean.fail("不存在该文件的分享"); 87 | } 88 | 89 | @Transactional(readOnly = true) 90 | public ShareInfoBean getShareFileInfoById(Long shareId) { 91 | if (shareId == null) { 92 | return null; 93 | } 94 | Map param = new HashMap(); 95 | param.put("shareId", shareId); 96 | List list = shareInfoDao.selectShareInfo(param); 97 | if (list == null || list.size() == 0) { 98 | return null; 99 | } 100 | 101 | return list.get(0); 102 | } 103 | 104 | @Transactional(readOnly = true) 105 | public List listUserShareInfos(Long userId, Integer status, int pageNum, int pageSize) { 106 | 107 | if (userId == null) { 108 | return new ArrayList(); 109 | } 110 | 111 | Map param = new HashMap(); 112 | param.put("userId", userId); 113 | if (status != null) { 114 | param.put("status", status); 115 | } 116 | param.put("index", (pageNum - 1) * pageSize); 117 | param.put("limit", pageSize); 118 | 119 | List list = shareInfoDao.selectShareInfo(param); 120 | 121 | return list; 122 | } 123 | 124 | public int countShareList(Long userId, Integer status) { 125 | 126 | Map param = new HashMap(); 127 | param.put("userId", userId); 128 | if (status != null) { 129 | param.put("status", status); 130 | } 131 | 132 | return shareInfoDao.countShareList(param); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/service/impl/ShortLinkServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service.impl; 2 | 3 | import com.pdwu.easycloud.file.service.IShortLinkService; 4 | import org.apache.commons.lang3.StringUtils; 5 | import org.springframework.stereotype.Service; 6 | 7 | /** 8 | * 短链接实现类 9 | * 使用数字转62进制的方式 10 | *

11 | * Created by pdwu on 2017/12/20. 12 | */ 13 | @Service 14 | public class ShortLinkServiceImpl implements IShortLinkService { 15 | 16 | private static final String standardArray = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 17 | private static final String myArray = "lmnopFGhijkNOPQRSTHwx45qyzABCDE67IJKLM0129abcdefgUVWXYZ3rstuv8"; 18 | 19 | private static String array = myArray; 20 | 21 | public static void setArrayToStandard() { 22 | ShortLinkServiceImpl.array = standardArray; 23 | } 24 | 25 | public static void setArrayToMine() { 26 | ShortLinkServiceImpl.array = myArray; 27 | } 28 | 29 | public String getShortLink(Long shareId) { 30 | StringBuilder str = new StringBuilder(); 31 | 32 | long num = shareId.longValue(); 33 | if (num == 0) { 34 | return array.charAt(0) + ""; 35 | } 36 | 37 | while (num != 0) { 38 | long rest = num - (num / 62) * 62; 39 | str.append(array.charAt((int) rest)); 40 | num = num / 62; 41 | } 42 | 43 | return str.reverse().toString(); 44 | } 45 | 46 | public Long getShareId(String shortLink) { 47 | if (StringUtils.isBlank(shortLink)) { 48 | return 0L; 49 | } 50 | 51 | long num = 0; 52 | int length = shortLink.length(); 53 | for (int i = length - 1; i >= 0; i--) { 54 | char c = shortLink.charAt(i); 55 | num = num + array.indexOf(c) * (long) Math.pow(62, length - i - 1); 56 | } 57 | 58 | return num; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/util/FileSizeSerialize.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.util; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.JsonSerializer; 6 | import com.fasterxml.jackson.databind.SerializerProvider; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * Created by pdwu on 2018/1/16. 12 | */ 13 | public class FileSizeSerialize extends JsonSerializer { 14 | 15 | public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { 16 | 17 | if (value == null) { 18 | gen.writeString("0B"); 19 | } else { 20 | gen.writeString(FileSizeUtils.getStringSize(value)); 21 | } 22 | 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/util/FileSizeUtils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.util; 2 | 3 | import java.math.BigDecimal; 4 | import java.text.DecimalFormat; 5 | 6 | /** 7 | * Created by pdwu on 2018/1/16. 8 | */ 9 | public class FileSizeUtils { 10 | 11 | public static String getStringSize(long size) { 12 | 13 | BigDecimal fileSize = new BigDecimal(size); 14 | BigDecimal param = new BigDecimal(1024); 15 | int count = 0; 16 | while(fileSize.compareTo(param) > 0 && count < 5) 17 | { 18 | fileSize = fileSize.divide(param); 19 | count++; 20 | } 21 | DecimalFormat df = new DecimalFormat("#.##"); 22 | String result = df.format(fileSize) + ""; 23 | switch (count) { 24 | case 0: 25 | result += "B"; 26 | break; 27 | case 1: 28 | result += "KB"; 29 | break; 30 | case 2: 31 | result += "MB"; 32 | break; 33 | case 3: 34 | result += "GB"; 35 | break; 36 | case 4: 37 | result += "TB"; 38 | break; 39 | case 5: 40 | result += "PB"; 41 | break; 42 | } 43 | return result; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/file/util/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.util; 2 | 3 | import org.springframework.util.DigestUtils; 4 | import org.springframework.web.multipart.MultipartFile; 5 | 6 | import java.io.IOException; 7 | 8 | /** 9 | * Created by pdwu on 2017/12/19. 10 | */ 11 | public class FileUtils extends org.apache.commons.io.FileUtils { 12 | 13 | public static String getFileMD5(MultipartFile file) throws IOException { 14 | if (file == null) { 15 | throw new NullPointerException(); 16 | } 17 | 18 | String digest = DigestUtils.md5DigestAsHex(file.getInputStream()); 19 | 20 | return digest; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/bean/TokenBean.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.bean; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | 5 | import java.util.Date; 6 | 7 | public class TokenBean { 8 | 9 | private String token; 10 | private Long userId; 11 | private Integer status; 12 | private Date createTime; 13 | private Date lastTime; 14 | 15 | public Date getLastTime() { 16 | return lastTime; 17 | } 18 | 19 | public void setLastTime(Date lastTime) { 20 | this.lastTime = lastTime; 21 | } 22 | 23 | public String getToken() { 24 | return token; 25 | } 26 | 27 | public void setToken(String token) { 28 | this.token = token; 29 | } 30 | 31 | public Long getUserId() { 32 | return userId; 33 | } 34 | 35 | public void setUserId(Long userId) { 36 | this.userId = userId; 37 | } 38 | 39 | public Date getCreateTime() { 40 | return createTime; 41 | } 42 | 43 | public void setCreateTime(Date createTime) { 44 | this.createTime = createTime; 45 | } 46 | 47 | public Integer getStatus() { 48 | return status; 49 | } 50 | 51 | public void setStatus(Integer status) { 52 | this.status = status; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/bean/UserBean.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.bean; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | 6 | import java.io.Serializable; 7 | import java.util.Date; 8 | 9 | /** 10 | * Created by pdwu on 2017/11/21. 11 | */ 12 | public class UserBean implements Serializable { 13 | 14 | private Long userId; 15 | private String account; 16 | private String password; 17 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 18 | private Date createTime; 19 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 20 | private Date lastTime; 21 | private String token; 22 | 23 | public Long getUserId() { 24 | return userId; 25 | } 26 | 27 | public void setUserId(Long userId) { 28 | this.userId = userId; 29 | } 30 | 31 | public String getAccount() { 32 | return account; 33 | } 34 | 35 | public void setAccount(String account) { 36 | this.account = account; 37 | } 38 | 39 | public String getPassword() { 40 | return password; 41 | } 42 | 43 | public void setPassword(String password) { 44 | this.password = password; 45 | } 46 | 47 | public Date getCreateTime() { 48 | return createTime; 49 | } 50 | 51 | public void setCreateTime(Date createTime) { 52 | this.createTime = createTime; 53 | } 54 | 55 | public Date getLastTime() { 56 | return lastTime; 57 | } 58 | 59 | public void setLastTime(Date lastTime) { 60 | this.lastTime = lastTime; 61 | } 62 | 63 | public String getToken() { 64 | return token; 65 | } 66 | 67 | public void setToken(String token) { 68 | this.token = token; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/constant/TokenConstant.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.constant; 2 | 3 | /** 4 | * Created by pdwu on 2017/12/16. 5 | */ 6 | public class TokenConstant { 7 | 8 | //token过期时间(单位:秒) 9 | public static final int OVERDUE_TIME_SECOND = 7200; 10 | 11 | public static final String COOKIE_NAME = "easycloud_token"; 12 | 13 | 14 | //token状态: 正常 15 | public static final int STATUS_NORMAL = 0; 16 | 17 | //token状态: 删除/过期 18 | public static final int STATUS_DELETE = 1; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.controller; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.SessionAttributeConstant; 5 | import com.pdwu.easycloud.common.config.AppConfig; 6 | import com.pdwu.easycloud.user.bean.TokenBean; 7 | import com.pdwu.easycloud.user.bean.UserBean; 8 | import com.pdwu.easycloud.user.constant.TokenConstant; 9 | import com.pdwu.easycloud.user.service.IUserService; 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.apache.ibatis.annotations.Param; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.stereotype.Controller; 16 | import org.springframework.web.bind.annotation.*; 17 | 18 | import javax.servlet.http.Cookie; 19 | import javax.servlet.http.HttpServletRequest; 20 | import javax.servlet.http.HttpServletResponse; 21 | import java.util.Map; 22 | 23 | /** 24 | * Created by pdwu on 2017/11/22. 25 | */ 26 | @Controller 27 | public class UserController { 28 | 29 | private Logger log = LoggerFactory.getLogger(UserController.class); 30 | 31 | @Autowired 32 | private IUserService userService; 33 | 34 | @RequestMapping(value = AppConfig.API_LOGIN, method = RequestMethod.POST) 35 | @ResponseBody 36 | public Object login(HttpServletRequest request, HttpServletResponse response, @RequestBody Map requestMap) { 37 | 38 | String account = requestMap.get("account"); 39 | if (StringUtils.isBlank(account)) { 40 | return ResultBean.fail("账户不能为空"); 41 | } 42 | String password = requestMap.get("password"); 43 | if (StringUtils.isBlank(password)) { 44 | return ResultBean.fail("密码不能为空"); 45 | } 46 | 47 | UserBean bean = userService.login(account, password); 48 | if (bean == null) { 49 | return ResultBean.fail("账户不存在或密码错误!"); 50 | } 51 | 52 | Cookie cookie = new Cookie(TokenConstant.COOKIE_NAME, bean.getToken()); 53 | cookie.setMaxAge(TokenConstant.OVERDUE_TIME_SECOND); 54 | cookie.setHttpOnly(true); 55 | cookie.setPath("/"); 56 | response.addCookie(cookie); 57 | 58 | return ResultBean.success(bean); 59 | } 60 | 61 | @RequestMapping(value = AppConfig.API_REGISTER, method = RequestMethod.POST) 62 | @ResponseBody 63 | public Object register(@RequestBody Map requestMap) { 64 | 65 | log.debug("/register request: {}", requestMap.toString()); 66 | 67 | 68 | if (StringUtils.isBlank(requestMap.get("account"))) { 69 | return ResultBean.fail("账户不能为空"); 70 | } 71 | if (StringUtils.isBlank(requestMap.get("password"))) { 72 | return ResultBean.fail("密码不能为空"); 73 | } 74 | return this.userService.register(requestMap.get("account"), requestMap.get("password")); 75 | } 76 | 77 | @RequestMapping(value = AppConfig.API_LOGOUT) 78 | @ResponseBody 79 | public Object logout(HttpServletRequest request, String token) { 80 | 81 | String trueToken = (String) request.getSession().getAttribute(SessionAttributeConstant.TOKEN); 82 | 83 | if (!StringUtils.isBlank(token)) { 84 | trueToken = token; 85 | } 86 | 87 | return this.userService.logout(trueToken); 88 | 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/dao/TokenDao.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.dao; 2 | 3 | import com.pdwu.easycloud.user.bean.TokenBean; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public interface TokenDao { 9 | 10 | /** 11 | * 查找token 12 | * @param param (可指定token,userId,status, 并集) 13 | * @return 14 | */ 15 | List selectToken(Map param); 16 | 17 | int insertToken(TokenBean bean); 18 | 19 | int updateTokenStatus(Map param); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/dao/TokenDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | INSERT INTO user_token (user_id, token, create_time, last_time, status) 16 | VALUES (#{userId}, #{token}, #{createTime}, #{lastTime}, #{status}) 17 | 18 | 19 | 20 | 41 | 42 | 43 | 44 | UPDATE user_token SET status=#{status} 45 | 46 | 47 | 48 | token = #{token} 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.dao; 2 | 3 | import com.pdwu.easycloud.user.bean.UserBean; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by pdwu on 2017/11/21. 10 | */ 11 | public interface UserDao { 12 | 13 | void insertUser(UserBean userBean); 14 | 15 | UserBean selectUserByAccountAndPassword(UserBean userBean); 16 | 17 | int selectUserAccountCount(String account); 18 | 19 | List selectUserInfo(Map map); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/dao/UserDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 23 | 24 | 37 | 38 | 60 | 61 | 62 | 63 | 64 | INSERT INTO user_info (account, password, create_time, last_time) 65 | VALUES (#{account}, #{password}, #{createTime}, #{lastTime}) 66 | 67 | 68 | 69 | 70 | 71 | DELETE FROM user_info 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/interceptor/LoginInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.interceptor; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.ResultCode; 5 | import com.pdwu.easycloud.common.bean.SessionAttributeConstant; 6 | import com.pdwu.easycloud.common.util.JsonUtils; 7 | import com.pdwu.easycloud.common.util.WebUtils; 8 | import com.pdwu.easycloud.user.bean.TokenBean; 9 | import com.pdwu.easycloud.user.constant.TokenConstant; 10 | import com.pdwu.easycloud.user.service.ITokenService; 11 | import org.apache.commons.lang3.StringUtils; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.web.servlet.HandlerInterceptor; 16 | import org.springframework.web.servlet.ModelAndView; 17 | 18 | import javax.servlet.http.Cookie; 19 | import javax.servlet.http.HttpServletRequest; 20 | import javax.servlet.http.HttpServletResponse; 21 | import java.io.IOException; 22 | import java.io.PrintWriter; 23 | 24 | public class LoginInterceptor implements HandlerInterceptor { 25 | 26 | @Autowired 27 | private ITokenService tokenService; 28 | 29 | private Logger log = LoggerFactory.getLogger(getClass()); 30 | 31 | public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { 32 | 33 | log.debug("preHandle.RequestURI: {}", httpServletRequest.getRequestURI()); 34 | 35 | boolean isPublic = WebUtils.checkUriPublic(httpServletRequest.getRequestURI()); 36 | 37 | String token = getTokenFromRequest(httpServletRequest); 38 | 39 | log.debug("preHandle.getTokenFromRequest.token: {}", token); 40 | 41 | 42 | //1. 不带token 43 | if (StringUtils.isBlank(token)) { 44 | //公共接口,可通过; 否则拦截 45 | return isPublic || returnTokenInvalid(httpServletRequest, httpServletResponse, o); 46 | } 47 | 48 | //2. 带了token,则认证 49 | ResultBean resultBean = tokenService.checkTokenValid(token); 50 | 51 | //2.1 token无效 52 | if (resultBean.getCode() != ResultCode.ok) { 53 | //公共接口,可通过; 否则拦截 54 | return isPublic || returnTokenInvalid(httpServletRequest, httpServletResponse, o); 55 | } 56 | 57 | //2.2 有效 58 | TokenBean tokenBean = (TokenBean) resultBean.getData(); 59 | httpServletRequest.getSession().setAttribute("userId", tokenBean.getUserId()); 60 | httpServletRequest.getSession().setAttribute(SessionAttributeConstant.TOKEN, token); 61 | 62 | return true; 63 | } 64 | 65 | public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { 66 | 67 | } 68 | 69 | public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { 70 | 71 | } 72 | 73 | private String getTokenFromRequest(HttpServletRequest request) { 74 | 75 | String authorization = request.getHeader("Authorization"); 76 | if (!StringUtils.isBlank(authorization)) { 77 | return authorization; 78 | } 79 | 80 | Cookie[] cookies = request.getCookies(); 81 | if (cookies != null) { 82 | for (Cookie c : cookies) { 83 | if (c.getName().equals(TokenConstant.COOKIE_NAME)) { 84 | return c.getValue(); 85 | } 86 | } 87 | } 88 | 89 | 90 | return ""; 91 | } 92 | 93 | private boolean returnTokenInvalid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws IOException { 94 | 95 | httpServletResponse.setStatus(ResultCode.unauthorized); 96 | 97 | PrintWriter writer = httpServletResponse.getWriter(); 98 | 99 | writer.write(JsonUtils.objectToJson(ResultBean.fail(ResultCode.unauthorized, "please login"))); 100 | 101 | return false; 102 | 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/service/ITokenService.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.service; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.user.bean.TokenBean; 5 | 6 | public interface ITokenService { 7 | 8 | /** 9 | * 为用户生成一个token 10 | * 11 | * @param userId 12 | * @return 新token 13 | */ 14 | TokenBean addToken(Long userId); 15 | 16 | /** 17 | * 检查token是否有效 18 | * 19 | * @param token 20 | * @return code=1: 失效 21 | */ 22 | ResultBean checkTokenValid(String token); 23 | 24 | /** 25 | * 更新token状态 26 | * 27 | * @param token 28 | * @param status 29 | * @return 30 | */ 31 | ResultBean updateTokenStatus(String token, Integer status); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/service/IUserService.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.service; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.user.bean.UserBean; 5 | 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by pdwu on 2017/12/9. 10 | */ 11 | public interface IUserService { 12 | 13 | /** 14 | * 登录 15 | * 16 | * @param account 账户 17 | * @param password 密码 18 | * @return 19 | */ 20 | UserBean login(String account, String password); 21 | 22 | /** 23 | * 注册 24 | * 25 | * @param account 账户 26 | * @param password 密码 27 | * @return 28 | */ 29 | ResultBean register(String account, String password); 30 | 31 | /** 32 | * 注销 33 | * 34 | * @param token 35 | * @return 36 | */ 37 | ResultBean logout(String token); 38 | 39 | /** 40 | * 获取用户信息 41 | * 42 | * @param map 可传入 userId, account 43 | * @return 44 | */ 45 | UserBean getUserInfo(Map map); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/service/impl/TokenServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.service.impl; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.util.UuidUtils; 5 | import com.pdwu.easycloud.user.bean.TokenBean; 6 | import com.pdwu.easycloud.user.constant.TokenConstant; 7 | import com.pdwu.easycloud.user.dao.TokenDao; 8 | import com.pdwu.easycloud.user.service.ITokenService; 9 | import com.pdwu.easycloud.user.util.TokenUtils; 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.transaction.annotation.Transactional; 14 | 15 | import java.util.Date; 16 | import java.util.HashMap; 17 | import java.util.List; 18 | import java.util.Map; 19 | 20 | @Service 21 | public class TokenServiceImpl implements ITokenService { 22 | 23 | @Autowired 24 | private TokenDao tokenDao; 25 | 26 | @Transactional 27 | public TokenBean addToken(Long userId) { 28 | 29 | TokenBean bean = new TokenBean(); 30 | bean.setUserId(userId); 31 | bean.setStatus(TokenConstant.STATUS_NORMAL); 32 | bean.setToken(UuidUtils.newUUID()); 33 | Date date = new Date(); 34 | bean.setCreateTime(date); 35 | bean.setLastTime(date); 36 | this.tokenDao.insertToken(bean); 37 | 38 | return bean; 39 | } 40 | 41 | @Transactional(readOnly = true) 42 | public ResultBean checkTokenValid(String token) { 43 | if (StringUtils.isBlank(token)) { 44 | return ResultBean.ARG_ERROR; 45 | } 46 | 47 | Map map = new HashMap(); 48 | map.put("token", token); 49 | map.put("status", TokenConstant.STATUS_NORMAL); 50 | List list = this.tokenDao.selectToken(map); 51 | if (list == null || list.size() == 0) { 52 | return ResultBean.fail(1, "Token已失效"); 53 | } 54 | 55 | boolean overdue = TokenUtils.isOverDue(list.get(0)); 56 | if (overdue) { 57 | return ResultBean.fail(1, "Token已失效"); 58 | } 59 | 60 | return ResultBean.success(list.get(0)); 61 | } 62 | 63 | @Transactional 64 | public ResultBean updateTokenStatus(String token, Integer status) { 65 | if (StringUtils.isBlank(token) || status == null) { 66 | return ResultBean.ARG_ERROR; 67 | } 68 | Map param = new HashMap(); 69 | param.put("token", token); 70 | param.put("status", status); 71 | int updatedCount = this.tokenDao.updateTokenStatus(param); 72 | 73 | if (updatedCount == 0) { 74 | return ResultBean.fail("token不存在"); 75 | } 76 | 77 | return ResultBean.success(""); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.service.impl; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.bean.ResultCode; 5 | import com.pdwu.easycloud.common.util.MD5Utils; 6 | import com.pdwu.easycloud.user.bean.TokenBean; 7 | import com.pdwu.easycloud.user.bean.UserBean; 8 | import com.pdwu.easycloud.user.constant.TokenConstant; 9 | import com.pdwu.easycloud.user.dao.UserDao; 10 | import com.pdwu.easycloud.user.service.ITokenService; 11 | import com.pdwu.easycloud.user.service.IUserService; 12 | import org.apache.commons.lang3.StringUtils; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | 17 | import java.util.Date; 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | /** 22 | * Created by pdwu on 2017/12/9. 23 | */ 24 | @Service 25 | public class UserServiceImpl implements IUserService { 26 | 27 | @Autowired 28 | private UserDao userDao; 29 | 30 | @Autowired 31 | private ITokenService tokenService; 32 | 33 | @Transactional() 34 | public UserBean login(String account, String password) { 35 | 36 | if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) { 37 | return null; 38 | } 39 | 40 | UserBean arg = new UserBean(); 41 | arg.setAccount(account); 42 | //获取密码的md5摘要 43 | String passwordMd5 = MD5Utils.getStringMd5(password); 44 | arg.setPassword(passwordMd5); 45 | 46 | UserBean userBean = this.userDao.selectUserByAccountAndPassword(arg); 47 | 48 | if (userBean == null) { 49 | return null; 50 | } 51 | 52 | TokenBean tokenBean = tokenService.addToken(userBean.getUserId()); 53 | userBean.setToken(tokenBean.getToken()); 54 | 55 | return userBean; 56 | } 57 | 58 | @Transactional 59 | public ResultBean register(String account, String password) { 60 | 61 | if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) { 62 | return ResultBean.ARG_ERROR; 63 | } 64 | 65 | int count = this.userDao.selectUserAccountCount(account); 66 | if (count > 0) { 67 | return ResultBean.fail("账号已存在"); 68 | } 69 | 70 | UserBean bean = new UserBean(); 71 | bean.setAccount(account); 72 | //保存密码的md5摘要 73 | String passwordMd5 = MD5Utils.getStringMd5(password); 74 | bean.setPassword(passwordMd5); 75 | 76 | Date date = new Date(); 77 | bean.setCreateTime(date); 78 | bean.setLastTime(date); 79 | 80 | this.userDao.insertUser(bean); 81 | 82 | return ResultBean.success("注册成功"); 83 | 84 | } 85 | 86 | @Transactional 87 | public ResultBean logout(String token) { 88 | 89 | ResultBean resultBean = this.tokenService.updateTokenStatus(token, TokenConstant.STATUS_DELETE); 90 | if (resultBean.getCode() == ResultCode.ok) { 91 | return ResultBean.success("注销成功"); 92 | } 93 | 94 | return resultBean; 95 | } 96 | 97 | public UserBean getUserInfo(Map map) { 98 | if (map == null) return null; 99 | 100 | List list = this.userDao.selectUserInfo(map); 101 | if (list == null || list.size() == 0) { 102 | return null; 103 | } 104 | 105 | return list.get(0); 106 | } 107 | 108 | 109 | } 110 | -------------------------------------------------------------------------------- /server/src/main/java/com/pdwu/easycloud/user/util/TokenUtils.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.util; 2 | 3 | import com.pdwu.easycloud.user.bean.TokenBean; 4 | import com.pdwu.easycloud.user.constant.TokenConstant; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | public class TokenUtils { 8 | 9 | public static boolean isOverDue(TokenBean bean) { 10 | if (bean == null || StringUtils.isBlank(bean.getToken()) || bean.getCreateTime() == null) { 11 | return true; 12 | } 13 | 14 | // 与当前时间间隔 15 | long d = System.currentTimeMillis() - bean.getCreateTime().getTime(); 16 | d = d / 1000; 17 | 18 | return d > TokenConstant.OVERDUE_TIME_SECOND; 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /server/src/main/resources/app/easycloud.properties: -------------------------------------------------------------------------------- 1 | # 用户所上传的文件的统一保存目录 2 | app.file.userfilepath=D:\\easycloud\\userfiles\\ 3 | app.common.site=http://localhost:8080/ -------------------------------------------------------------------------------- /server/src/main/resources/db.properties: -------------------------------------------------------------------------------- 1 | jdbc.driver=com.mysql.jdbc.Driver 2 | jdbc.url=jdbc:mysql://localhost:3306/proj_easycloud?useUnicode=true&characterEncoding=utf8&autoReconnectForPools=true&autoReconnect=true 3 | jdbc.username=root 4 | jdbc.password=123456 -------------------------------------------------------------------------------- /server/src/main/resources/db/create_db.sql: -------------------------------------------------------------------------------- 1 | DROP DATABASE IF EXISTS proj_easycloud; 2 | CREATE DATABASE proj_easycloud; -------------------------------------------------------------------------------- /server/src/main/resources/db/create_table.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS user_info; 2 | 3 | # user_info 用户信息 4 | CREATE TABLE user_info ( 5 | user_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 6 | account VARCHAR(10) NOT NULL, 7 | password VARCHAR(64) NOT NULL, 8 | create_time DATETIME(3) NOT NULL, 9 | last_time DATETIME(3) NOT NULL 10 | 11 | ) 12 | ENGINE = INNODB 13 | AUTO_INCREMENT = 10001 14 | DEFAULT CHARSET = utf8; 15 | 16 | DROP TABLE IF EXISTS user_token; 17 | # user_token Token表 18 | CREATE TABLE user_token ( 19 | user_id BIGINT UNSIGNED, 20 | token VARCHAR(32) NOT NULL, 21 | status TINYINT DEFAULT 0, 22 | create_time DATETIME(3) NOT NULL, 23 | last_time DATETIME(3) NOT NULL 24 | 25 | ) 26 | ENGINE = INNODB 27 | DEFAULT CHARSET = utf8; 28 | 29 | DROP TABLE IF EXISTS file_info; 30 | # file_info 文件信息表 31 | CREATE TABLE file_info ( 32 | file_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 33 | user_id BIGINT UNSIGNED, 34 | md5 VARCHAR(32) NOT NULL, 35 | path VARCHAR(100) NOT NULL, 36 | name VARCHAR(60) NOT NULL, 37 | size INT UNSIGNED DEFAULT 0, 38 | status TINYINT DEFAULT 0, 39 | create_time DATETIME(3) NOT NULL, 40 | last_time DATETIME(3) NOT NULL 41 | ) 42 | ENGINE = INNODB 43 | AUTO_INCREMENT = 101 44 | DEFAULT CHARSET = utf8; 45 | 46 | 47 | DROP TABLE IF EXISTS share_info; 48 | # share_info 分享信息表 49 | CREATE TABLE share_info ( 50 | share_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 51 | user_id BIGINT UNSIGNED, 52 | file_id BIGINT UNSIGNED, 53 | password VARCHAR(10), 54 | shortlink VARCHAR(32), 55 | status TINYINT DEFAULT 0, 56 | create_time DATETIME(3) NOT NULL, 57 | last_time DATETIME(3) NOT NULL 58 | ) 59 | ENGINE = INNODB 60 | AUTO_INCREMENT = 1000001 61 | DEFAULT CHARSET = utf8; 62 | -------------------------------------------------------------------------------- /server/src/main/resources/db/h2/createTable.sql: -------------------------------------------------------------------------------- 1 | SET MODE MySQL; 2 | DROP TABLE IF EXISTS user_info; 3 | 4 | CREATE TABLE user_info ( 5 | user_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 6 | account VARCHAR(10) NOT NULL, 7 | password VARCHAR(64) NOT NULL, 8 | create_time DATETIME(3) NOT NULL, 9 | last_time DATETIME(3) NOT NULL 10 | 11 | ) 12 | ENGINE = INNODB 13 | AUTO_INCREMENT = 10001 14 | DEFAULT CHARSET = utf8; 15 | 16 | DROP TABLE IF EXISTS user_token; 17 | CREATE TABLE user_token ( 18 | user_id BIGINT UNSIGNED, 19 | token VARCHAR(32) NOT NULL, 20 | status TINYINT DEFAULT 0, 21 | create_time DATETIME(3) NOT NULL, 22 | last_time DATETIME(3) NOT NULL 23 | 24 | ) 25 | ENGINE = INNODB 26 | DEFAULT CHARSET = utf8; 27 | 28 | DROP TABLE IF EXISTS file_info; 29 | CREATE TABLE file_info ( 30 | file_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 31 | user_id BIGINT UNSIGNED, 32 | md5 VARCHAR(32) NOT NULL, 33 | path VARCHAR(100) NOT NULL, 34 | name VARCHAR(60) NOT NULL, 35 | size INT UNSIGNED DEFAULT 0, 36 | status TINYINT DEFAULT 0, 37 | create_time DATETIME(3) NOT NULL, 38 | last_time DATETIME(3) NOT NULL 39 | ) 40 | ENGINE = INNODB 41 | AUTO_INCREMENT = 101 42 | DEFAULT CHARSET = utf8; 43 | 44 | 45 | DROP TABLE IF EXISTS share_info; 46 | CREATE TABLE share_info ( 47 | share_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 48 | user_id BIGINT UNSIGNED, 49 | file_id BIGINT UNSIGNED, 50 | password VARCHAR(10), 51 | shortlink VARCHAR(32), 52 | status TINYINT DEFAULT 0, 53 | create_time DATETIME(3) NOT NULL, 54 | last_time DATETIME(3) NOT NULL 55 | ) 56 | ENGINE = INNODB 57 | AUTO_INCREMENT = 100001 58 | DEFAULT CHARSET = utf8; 59 | -------------------------------------------------------------------------------- /server/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | ### set log levels ### 2 | log4j.rootLogger = info , stdout , D , E 3 | 4 | ### output to the console ### 5 | log4j.appender.stdout = org.apache.log4j.ConsoleAppender 6 | log4j.appender.stdout.Target = System.out 7 | log4j.appender.stdout.layout = org.apache.log4j.PatternLayout 8 | log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%c:%L] [%p] - %m%n 9 | 10 | ### output mybatis sql info to the console ### 11 | log4j.logger.com.pdwu.easycloud=DEBUG 12 | log4j.logger.org.springframework.jdbc.datasource=DEBUG 13 | #log4j.logger.org.apache=DEBUG 14 | #log4j.logger.java.sql.Connection=DEBUG 15 | #log4j.logger.java.sql.Statement=DEBUG 16 | #log4j.logger.java.sql.PreparedStatement=DEBUG 17 | 18 | ### Output to the log file ### 19 | log4j.appender.D = org.apache.log4j.DailyRollingFileAppender 20 | log4j.appender.D.File = D:/myAppLogs/easycloud/log.log 21 | log4j.appender.D.Append = true 22 | log4j.appender.D.Threshold = debug 23 | log4j.appender.D.layout = org.apache.log4j.PatternLayout 24 | log4j.appender.D.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] [%c:%L] [%p] - %m%n 25 | 26 | ### Save exception information to separate file ### 27 | log4j.appender.E = org.apache.log4j.DailyRollingFileAppender 28 | log4j.appender.E.File = D:/myAppLogs/easycloud/error.log 29 | log4j.appender.E.Append = true 30 | log4j.appender.E.Threshold = warn 31 | log4j.appender.E.layout = org.apache.log4j.PatternLayout 32 | log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] [%c:%L] [%p] - %m%n -------------------------------------------------------------------------------- /server/src/main/resources/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /server/src/main/resources/spring/db-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /server/src/main/resources/spring/spring-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /server/src/main/resources/spring/spring-mvc.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | application/json;charset=UTF-8 29 | text/plain;charset=UTF-8 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /server/src/main/resources/spring/spring-mybatis.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 15 | 16 | 17 | 18 | classpath:db.properties 19 | 20 | file:/home/myAppConf/easycloud.db.properties 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /server/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | Easy Cloud 7 | 8 | 9 | 10 | 11 | contextConfigLocation 12 | classpath:spring/spring-context.xml 13 | 14 | 15 | 16 | 17 | org.springframework.web.context.ContextLoaderListener 18 | 19 | 20 | 21 | 22 | log4jConfigLocation 23 | classpath:properties/log4j.properties 24 | 25 | 26 | log4jRefreshInterval 27 | 6000 28 | 29 | 30 | 31 | 32 | encoding 33 | org.springframework.web.filter.CharacterEncodingFilter 34 | 35 | encoding 36 | UTF-8 37 | 38 | 39 | 40 | encoding 41 | /* 42 | 43 | 44 | 45 | 46 | dispatcherServlet 47 | org.springframework.web.servlet.DispatcherServlet 48 | 49 | contextConfigLocation 50 | classpath:spring/spring-mvc.xml 51 | 52 | 1 53 | 54 | 55 | dispatcherServlet 56 | / 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /server/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Hello World!

4 | 5 | 6 | -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/common/bean/BeanTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.bean; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * Created by pdwu on 2017/12/16. 7 | */ 8 | public class BeanTest { 9 | 10 | @Test 11 | public void test() { 12 | new ResultCode(); 13 | 14 | new ResultBean(1, "", "").toString(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/common/config/AppConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.config; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.test.context.ContextConfiguration; 7 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 | import org.springframework.test.context.web.WebAppConfiguration; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Created by pdwu on 2017/12/19. 14 | */ 15 | @RunWith(SpringJUnit4ClassRunner.class) 16 | @WebAppConfiguration("src/main/resources") 17 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml"}) 18 | public class AppConfigTest { 19 | 20 | @Autowired 21 | private AppConfig appConfig; 22 | 23 | @Test 24 | public void testAppConfig() { 25 | assertTrue(appConfig.getUserFilePath().length() > 2); 26 | assertTrue(!appConfig.getUserFilePath().contains("userfilepath")); 27 | System.out.println(appConfig.getUserFilePath()); 28 | 29 | new AppConfig(); 30 | new AppConfig().setUserFilePath(""); 31 | } 32 | 33 | 34 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/common/util/JsonUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.pdwu.easycloud.common.bean.ResultBean; 5 | import org.junit.Test; 6 | 7 | import java.io.IOException; 8 | import java.util.Map; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Created by pdwu on 2017/12/16. 14 | */ 15 | public class JsonUtilsTest { 16 | 17 | 18 | @Test 19 | public void objectToJson() throws Exception { 20 | 21 | String res = JsonUtils.objectToJson(ResultBean.fail(123, "fail")); 22 | assertEquals("{\"msg\":\"fail\",\"code\":123,\"data\":null}", res); 23 | 24 | String res2 = JsonUtils.objectToJson(ResultBean.success("hehe")); 25 | assertEquals("{\"msg\":\"\",\"code\":200,\"data\":\"hehe\"}", res2); 26 | 27 | new JsonUtils(); 28 | } 29 | 30 | @Test 31 | public void jsonToResultBean() throws Exception { 32 | 33 | String s = "{\"msg\":\"hi\",\"data\":\"dddd\",\"code\":200}"; 34 | ResultBean bean = JsonUtils.jsonToResultBean(s); 35 | assertEquals("hi", bean.getMsg()); 36 | assertEquals("dddd", bean.getData()); 37 | assertEquals(200, bean.getCode()); 38 | 39 | } 40 | 41 | @Test 42 | public void test() throws IOException { 43 | 44 | for (int i = 0; i < 100; i++) { 45 | String res = JsonUtils.objectToJson(ResultBean.fail(123, "fail")); 46 | assertEquals("{\"msg\":\"fail\",\"code\":123,\"data\":null}", res); 47 | 48 | String s = "{\"msg\":\"hi\",\"data\":\"dddd\",\"code\":200}"; 49 | ResultBean bean = JsonUtils.jsonToResultBean(s); 50 | assertEquals("hi", bean.getMsg()); 51 | assertEquals("dddd", bean.getData()); 52 | assertEquals(200, bean.getCode()); 53 | 54 | } 55 | 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/common/util/MD5UtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by pdwu on 2018/1/16. 9 | */ 10 | public class MD5UtilsTest { 11 | 12 | @Test 13 | public void getStringMd5() { 14 | 15 | try { 16 | String s = MD5Utils.getStringMd5(null); 17 | fail(); 18 | } catch (NullPointerException e) { 19 | 20 | } 21 | 22 | assertEquals("202cb962ac59075b964b07152d234b70", MD5Utils.getStringMd5("123")); 23 | 24 | assertEquals("900150983cd24fb0d6963f7d28e17f72", MD5Utils.getStringMd5("abc")); 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/common/util/UuidUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class UuidUtilsTest { 8 | 9 | @Test 10 | public void newUUID() { 11 | 12 | System.out.println(UuidUtils.newUUID()); 13 | 14 | new UuidUtils(); 15 | 16 | } 17 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/common/util/WebUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.common.util; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | /** 9 | * Created by pdwu on 2017/12/20. 10 | */ 11 | public class WebUtilsTest { 12 | @Before 13 | public void setUp() throws Exception { 14 | } 15 | 16 | @Test 17 | public void checkUriPublic() throws Exception { 18 | new WebUtils(); 19 | 20 | assertTrue(!WebUtils.checkUriPublic("")); 21 | 22 | assertTrue(WebUtils.checkUriPublic("/api/pub")); 23 | assertTrue(WebUtils.checkUriPublic("/api/pube")); 24 | assertTrue(WebUtils.checkUriPublic("/api/pub/asdf")); 25 | assertTrue(WebUtils.checkUriPublic("/api/pub/f/ff")); 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/controller/DownloadControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.controller; 2 | 3 | import com.pdwu.easycloud.common.bean.ResultBean; 4 | import com.pdwu.easycloud.common.config.AppConfig; 5 | import com.pdwu.easycloud.file.bean.FileInfoBean; 6 | import com.pdwu.easycloud.file.service.IDownloadService; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.experimental.results.ResultMatchers; 10 | import org.junit.runner.RunWith; 11 | import org.mockito.InjectMocks; 12 | import org.mockito.Mock; 13 | import org.mockito.Mockito; 14 | import org.mockito.MockitoAnnotations; 15 | import org.springframework.mock.web.MockHttpSession; 16 | import org.springframework.test.context.ContextConfiguration; 17 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 18 | import org.springframework.test.context.web.WebAppConfiguration; 19 | import org.springframework.test.web.servlet.MockMvc; 20 | import org.springframework.test.web.servlet.result.HeaderResultMatchers; 21 | import org.springframework.test.web.servlet.result.RequestResultMatchers; 22 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 23 | 24 | import java.io.File; 25 | import java.util.HashMap; 26 | import java.util.Map; 27 | 28 | import static org.hamcrest.CoreMatchers.equalTo; 29 | import static org.hamcrest.CoreMatchers.is; 30 | import static org.junit.Assert.*; 31 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 32 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 33 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 34 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 35 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 36 | 37 | /** 38 | * Created by pdwu on 2017/12/21. 39 | */ 40 | @RunWith(SpringJUnit4ClassRunner.class) 41 | @WebAppConfiguration("src/main/resources") 42 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml"}) 43 | public class DownloadControllerTest { 44 | 45 | @InjectMocks 46 | private DownloadController controller; 47 | 48 | @Mock 49 | private IDownloadService downloadService; 50 | 51 | private MockMvc mockMvc; 52 | 53 | 54 | @Before 55 | public void setUp() throws Exception { 56 | MockitoAnnotations.initMocks(this); 57 | mockMvc = MockMvcBuilders.standaloneSetup(controller) 58 | .build(); 59 | } 60 | 61 | @Test 62 | public void download() throws Exception { 63 | 64 | Mockito.when(downloadService.download(1L, 1L, 1L, null)) 65 | .thenReturn(ResultBean.fail(404, "notfound中文不乱码")); 66 | Mockito.when(downloadService.download(1L, null, null, null)) 67 | .thenReturn(ResultBean.fail(404, "notfound")); 68 | 69 | MockHttpSession session = new MockHttpSession(); 70 | session.setAttribute("userId", 1L); 71 | 72 | mockMvc.perform(get(AppConfig.API_PUB_DOWNLOAD) 73 | .session(session) 74 | .param("fileId", "1") 75 | .param("shareId", "1")) 76 | .andDo(print()) 77 | .andExpect(jsonPath("$.code", is(404))) 78 | .andExpect(jsonPath("$.msg", equalTo("notfound中文不乱码"))); 79 | 80 | mockMvc.perform(get(AppConfig.API_PUB_DOWNLOAD) 81 | .session(session) 82 | .param("fileId", "") 83 | .param("shareId", "")) 84 | .andDo(print()) 85 | .andExpect(jsonPath("$.code", is(404))) 86 | .andExpect(jsonPath("$.msg", equalTo("notfound"))); 87 | 88 | 89 | //测试成功下载文件 90 | File file = new File("abc.txt"); 91 | file.createNewFile(); 92 | 93 | Map map = new HashMap(); 94 | FileInfoBean fileInfoBean = new FileInfoBean(); 95 | fileInfoBean.setName("xxx.jpg"); 96 | map.put("fileInfo", fileInfoBean); 97 | map.put("file", file); 98 | Mockito.when(downloadService.download(1L, 2L, 3L, null)).thenReturn(ResultBean.success(map)); 99 | 100 | mockMvc.perform(get(AppConfig.API_PUB_DOWNLOAD) 101 | .session(session) 102 | .param("fileId", "2") 103 | .param("shareId", "3")) 104 | .andDo(print()) 105 | .andExpect(status().is(200)); 106 | 107 | file.deleteOnExit(); 108 | 109 | } 110 | 111 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/controller/PublicShareControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.controller; 2 | 3 | import com.pdwu.easycloud.common.config.AppConfig; 4 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 5 | import com.pdwu.easycloud.file.service.IShareService; 6 | import com.pdwu.easycloud.file.service.IShortLinkService; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.mockito.InjectMocks; 11 | import org.mockito.Mock; 12 | import org.mockito.Mockito; 13 | import org.mockito.MockitoAnnotations; 14 | import org.springframework.test.context.ContextConfiguration; 15 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 16 | import org.springframework.test.context.web.WebAppConfiguration; 17 | import org.springframework.test.web.servlet.MockMvc; 18 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 19 | 20 | import static org.hamcrest.CoreMatchers.is; 21 | import static org.junit.Assert.*; 22 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; 23 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 24 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 25 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 26 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 27 | 28 | /** 29 | * Created by pdwu on 2017/12/20. 30 | */ 31 | @RunWith(SpringJUnit4ClassRunner.class) 32 | @WebAppConfiguration("src/main/resources") 33 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml"}) 34 | public class PublicShareControllerTest { 35 | 36 | @InjectMocks 37 | private PublicShareController controller; 38 | 39 | @Mock 40 | private IShareService shareService; 41 | @Mock 42 | private IShortLinkService shortLinkService; 43 | 44 | private MockMvc mockMvc; 45 | 46 | @Before 47 | public void setUp() throws Exception { 48 | MockitoAnnotations.initMocks(this); 49 | mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); 50 | } 51 | 52 | @Test 53 | public void getShareFile() throws Exception { 54 | Mockito.when(shortLinkService.getShareId("shortlinkabc")).thenReturn(123L); 55 | Mockito.when(shortLinkService.getShareId("shortlinkefg")).thenReturn(456L); 56 | Mockito.when(shareService.getShareFileInfoById(123L)).thenReturn(null); 57 | Mockito.when(shareService.getShareFileInfoById(456L)).thenReturn(new ShareInfoBean()); 58 | 59 | //文件已取消分享或不存在 60 | mockMvc.perform(get(AppConfig.API_PUB_SHARE + "/shortlinkabc")) 61 | .andDo(print()) 62 | .andExpect(jsonPath("$.code", is(404))); 63 | 64 | //正常 65 | mockMvc.perform(get(AppConfig.API_PUB_SHARE + "/shortlinkefg")) 66 | .andDo(print()) 67 | .andExpect(jsonPath("$.code", is(200))); 68 | 69 | } 70 | 71 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/service/impl/DownloadServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service.impl; 2 | 3 | import com.ninja_squad.dbsetup.DbSetup; 4 | import com.ninja_squad.dbsetup.DbSetupTracker; 5 | import com.ninja_squad.dbsetup.Operations; 6 | import com.ninja_squad.dbsetup.destination.DataSourceDestination; 7 | import com.ninja_squad.dbsetup.operation.Operation; 8 | import com.pdwu.easycloud.common.bean.ResultCode; 9 | import com.pdwu.easycloud.file.constant.FileInfoConstant; 10 | import com.pdwu.easycloud.file.constant.ShareInfoConstant; 11 | import com.pdwu.easycloud.file.service.IDownloadService; 12 | import org.junit.Before; 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.test.context.ContextConfiguration; 17 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 18 | import org.springframework.test.context.web.WebAppConfiguration; 19 | 20 | import javax.sql.DataSource; 21 | 22 | import java.util.Date; 23 | 24 | import static com.ninja_squad.dbsetup.Operations.sequenceOf; 25 | import static org.junit.Assert.*; 26 | 27 | /** 28 | * Created by pdwu on 2017/12/21. 29 | */ 30 | @RunWith(SpringJUnit4ClassRunner.class) 31 | @WebAppConfiguration("src/main/resources") 32 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml","classpath:spring/db-test.xml"}) 33 | public class DownloadServiceImplTest { 34 | 35 | public static DbSetupTracker dbSetupTracker = new DbSetupTracker(); 36 | 37 | @Autowired 38 | private DataSource dataSource; 39 | 40 | @Autowired 41 | private IDownloadService downloadService; 42 | 43 | @Before 44 | public void setUp() throws Exception { 45 | Operation operation = sequenceOf( 46 | Operations.deleteAllFrom("file_info", "share_info"), 47 | Operations.insertInto("file_info") 48 | .columns("FILE_ID", "USER_ID", "MD5", "PATH", "NAME", "STATUS", "CREATE_TIME", "LAST_TIME") 49 | .values(101L, 10011L, "793914c9c583d9d86d0f4ed8c521b0c1", "/file/10011/", "1513317967830.png", FileInfoConstant.STATUS_DELETE, new Date(1513317967830L), new Date(1513317967830L)) 50 | .values(102L, 10011L, "c28cbd398a61e9022fd6a6835a57dc50", "/file/10011/", "1513317967833.zip", FileInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 51 | .values(103L, 10012L, "099b3b060154898840f0ebdfb46ec78f", "/file/10012/", "1513317967835.png", FileInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 52 | .values(104L, 10013L, "3b060154898840f0ebdfb46ec78f099b", "/file/10013/", "1513317967888.png", FileInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 53 | .build(), 54 | Operations.insertInto("share_info") 55 | .columns("SHARE_ID", "FILE_ID", "USER_ID", "STATUS", "CREATE_TIME", "LAST_TIME") 56 | .values(100001L, 101L, 10011L, ShareInfoConstant.STATUS_CANCLE, new Date(1513926315000L), new Date(1513926315000L)) 57 | .values(100012L, 102L, 10011L, ShareInfoConstant.STATUS_CANCLE, new Date(1513317967830L), new Date(1513317967830L)) 58 | .values(100123L, 103L, 10012L, ShareInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 59 | .values(102224L, 104L, 10011L, ShareInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 60 | .build() 61 | ); 62 | 63 | DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); 64 | dbSetupTracker.launchIfNecessary(dbSetup); 65 | 66 | } 67 | 68 | @Test 69 | public void download() throws Exception { 70 | 71 | //1.1 文件不存在,真木有 72 | assertEquals(ResultCode.not_found, downloadService.download(null, 199L, null, null).getCode()); 73 | 74 | //1.2 文件不存在,逻辑删除 STATUS_DELETE 75 | assertEquals(ResultCode.not_found, downloadService.download(null, 101L, null, null).getCode()); 76 | 77 | //2.1.a 文件存在,但不是该用户的,也未分享 78 | assertEquals(ResultCode.not_found, downloadService.download(10099L, 102L, null, null).getCode()); 79 | 80 | //2.1.b 文件存在,但不是该用户的;文件主人确实分享了 81 | assertEquals(200, downloadService.download(10099L, 103L, 100123L, null).getCode()); 82 | 83 | //2.1.c 文件存在,但不是该用户的;文件主人取消分享了 84 | assertEquals(ResultCode.not_found, downloadService.download(10099L, 102L, 100012L, null).getCode()); 85 | 86 | //2.2 文件存在,是本用户的 87 | assertEquals(200, downloadService.download(10011L, 102L, null, null).getCode()); 88 | 89 | } 90 | 91 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/service/impl/ShareServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service.impl; 2 | 3 | import com.ninja_squad.dbsetup.DbSetup; 4 | import com.ninja_squad.dbsetup.DbSetupTracker; 5 | import com.ninja_squad.dbsetup.Operations; 6 | import com.ninja_squad.dbsetup.destination.DataSourceDestination; 7 | import com.ninja_squad.dbsetup.operation.Operation; 8 | import com.pdwu.easycloud.file.bean.ShareInfoBean; 9 | import com.pdwu.easycloud.file.constant.FileInfoConstant; 10 | import com.pdwu.easycloud.file.constant.ShareInfoConstant; 11 | import com.pdwu.easycloud.file.service.IShareService; 12 | import org.junit.Before; 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.test.context.ContextConfiguration; 17 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 18 | import org.springframework.test.context.web.WebAppConfiguration; 19 | 20 | import javax.sql.DataSource; 21 | 22 | import java.util.Date; 23 | import java.util.List; 24 | 25 | import static com.ninja_squad.dbsetup.Operations.sequenceOf; 26 | import static org.junit.Assert.*; 27 | 28 | /** 29 | * Created by pdwu on 2017/12/19. 30 | */ 31 | @RunWith(SpringJUnit4ClassRunner.class) 32 | @WebAppConfiguration("src/main/resources") 33 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml", "classpath:spring/db-test.xml"}) 34 | public class ShareServiceImplTest { 35 | 36 | 37 | public static DbSetupTracker dbSetupTracker = new DbSetupTracker(); 38 | 39 | @Autowired 40 | private DataSource dataSource; 41 | 42 | @Autowired 43 | private IShareService shareService; 44 | 45 | @Before 46 | public void setUp() throws Exception { 47 | Operation operation = sequenceOf( 48 | Operations.deleteAllFrom("file_info", "share_info"), 49 | Operations.insertInto("file_info") 50 | .columns("FILE_ID", "USER_ID", "MD5", "PATH", "NAME", "STATUS", "CREATE_TIME", "LAST_TIME") 51 | .values(101L, 10011L, "793914c9c583d9d86d0f4ed8c521b0c1", "/file/10011/", "1513317967830.png", FileInfoConstant.STATUS_DELETE, new Date(1513317967830L), new Date(1513317967830L)) 52 | .values(102L, 10011L, "c28cbd398a61e9022fd6a6835a57dc50", "/file/10011/", "1513317967833.zip", FileInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 53 | .values(103L, 10012L, "099b3b060154898840f0ebdfb46ec78f", "/file/10012/", "1513317967835.png", FileInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 54 | .values(104L, 10013L, "3b060154898840f0ebdfb46ec78f099b", "/file/10013/", "1513317967888.png", FileInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 55 | .build(), 56 | Operations.insertInto("share_info") 57 | .columns("SHARE_ID", "FILE_ID", "USER_ID", "STATUS", "CREATE_TIME", "LAST_TIME") 58 | .values(100001L, 101L, 10011L, ShareInfoConstant.STATUS_CANCLE, new Date(1513926315000L), new Date(1513926315000L)) 59 | .values(100012L, 102L, 10011L, ShareInfoConstant.STATUS_CANCLE, new Date(1513317967830L), new Date(1513317967830L)) 60 | .values(100123L, 103L, 10012L, ShareInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 61 | .values(102224L, 104L, 10011L, ShareInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 62 | .values(103224L, 1055L, 100112L, ShareInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 63 | .values(104224L, 1055L, 100112L, ShareInfoConstant.STATUS_NORMAL, new Date(1513317967830L), new Date(1513317967830L)) 64 | .build() 65 | ); 66 | 67 | DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); 68 | dbSetupTracker.launchIfNecessary(dbSetup); 69 | } 70 | 71 | @Test 72 | public void insertShareInfo() throws Exception { 73 | //arg 74 | assertEquals(400, shareService.insertShareInfo(null, null).getCode()); 75 | 76 | assertEquals(200, shareService.insertShareInfo(10099L, 105L).getCode()); 77 | } 78 | 79 | @Test 80 | public void deleteShareInfo() throws Exception { 81 | //arg 82 | assertEquals(400, shareService.deleteShareInfo(null).getCode()); 83 | 84 | //成功 85 | assertEquals(200, shareService.deleteShareInfo(100123L).getCode()); 86 | 87 | //shareId不存在 88 | assertEquals(400, shareService.deleteShareInfo(100999L).getCode()); 89 | } 90 | 91 | @Test 92 | public void deleteShareInfoByFileId() throws Exception { 93 | 94 | //arg 95 | assertEquals(400, shareService.deleteShareInfoByFileId(null).getCode()); 96 | 97 | //成功 98 | assertEquals(200, shareService.deleteShareInfoByFileId(1055L).getCode()); 99 | 100 | //file不存在 101 | assertEquals(400, shareService.deleteShareInfoByFileId(100999L).getCode()); 102 | } 103 | 104 | @Test 105 | public void getShareFileInfoById() throws Exception { 106 | 107 | //arg 108 | assertNull(shareService.getShareFileInfoById(null)); 109 | 110 | //成功 111 | ShareInfoBean bean = shareService.getShareFileInfoById(100123L); 112 | assertEquals(103L, bean.getFileId().longValue()); 113 | assertEquals(103L, bean.getFileInfo().getFileId().longValue()); 114 | assertEquals("099b3b060154898840f0ebdfb46ec78f", bean.getFileInfo().getMd5()); 115 | 116 | //不存在 117 | assertNull(shareService.getShareFileInfoById(100999L)); 118 | } 119 | 120 | @Test 121 | public void listUserShareInfos() throws Exception { 122 | 123 | //arg 124 | List list = shareService.listUserShareInfos(null, null, 1, 10); 125 | assertEquals(0, list.size()); 126 | 127 | //用户10011L 128 | List list1 = shareService.listUserShareInfos(10011L, null, 1, 10); 129 | assertEquals(3, list1.size()); 130 | 131 | 132 | //用户10011L, STATUS_CANCLE 133 | List list2 = shareService.listUserShareInfos(10011L, ShareInfoConstant.STATUS_CANCLE, 1, 10); 134 | assertEquals(2, list2.size()); 135 | assertEquals(101L, list2.get(0).getFileId().longValue()); 136 | assertEquals(102L, list2.get(1).getFileId().longValue()); 137 | 138 | 139 | //用户10011L, STATUS_NORMAL 140 | List list3 = shareService.listUserShareInfos(10011L, ShareInfoConstant.STATUS_NORMAL, 1, 10); 141 | assertEquals(1, list3.size()); 142 | assertEquals(104L, list3.get(0).getFileId().longValue()); 143 | } 144 | 145 | @Test 146 | public void countShareList() throws Exception { 147 | 148 | assertEquals(6, shareService.countShareList(null, null)); 149 | 150 | assertEquals(3, shareService.countShareList(10011L, null)); 151 | 152 | assertEquals(1, shareService.countShareList(10011L, ShareInfoConstant.STATUS_NORMAL)); 153 | 154 | } 155 | 156 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/service/impl/ShortLinkServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.service.impl; 2 | 3 | import com.pdwu.easycloud.file.service.IShortLinkService; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.test.context.ContextConfiguration; 9 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 | import org.springframework.test.context.web.WebAppConfiguration; 11 | 12 | import static org.junit.Assert.*; 13 | 14 | /** 15 | * Created by pdwu on 2017/12/20. 16 | */ 17 | @RunWith(SpringJUnit4ClassRunner.class) 18 | @WebAppConfiguration("src/main/resources") 19 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml"}) 20 | public class ShortLinkServiceImplTest { 21 | 22 | @Autowired 23 | private ShortLinkServiceImpl shortLinkService; 24 | 25 | @Before 26 | public void setUp() throws Exception { 27 | } 28 | 29 | @Test 30 | public void getShortLink() throws Exception { 31 | ShortLinkServiceImpl.setArrayToMine(); //自定的62进制排列 32 | ShortLinkServiceImpl.setArrayToStandard();//标准排列 33 | 34 | 35 | assertEquals("0", shortLinkService.getShortLink(0L)); 36 | assertEquals("1", shortLinkService.getShortLink(1L)); 37 | assertEquals("Z", shortLinkService.getShortLink(61L)); 38 | assertEquals("10", shortLinkService.getShortLink(62L)); 39 | assertEquals("11", shortLinkService.getShortLink(63L)); 40 | assertEquals("g8", shortLinkService.getShortLink(1000L)); 41 | assertEquals("3d7", shortLinkService.getShortLink(12345L)); 42 | assertEquals("2zix", shortLinkService.getShortLink(612345L)); 43 | assertEquals("5ban", shortLinkService.getShortLink(1234567L)); 44 | 45 | } 46 | 47 | @Test 48 | public void getShareId() throws Exception { 49 | ShortLinkServiceImpl.setArrayToStandard(); 50 | 51 | assertEquals(0L, shortLinkService.getShareId("").longValue()); 52 | assertEquals(0L, shortLinkService.getShareId("0").longValue()); 53 | assertEquals(1L, shortLinkService.getShareId("1").longValue()); 54 | assertEquals(61L, shortLinkService.getShareId("Z").longValue()); 55 | assertEquals(62L, shortLinkService.getShareId("10").longValue()); 56 | assertEquals(63L, shortLinkService.getShareId("11").longValue()); 57 | assertEquals(1000L, shortLinkService.getShareId("g8").longValue()); 58 | assertEquals(12345L, shortLinkService.getShareId("3d7").longValue()); 59 | assertEquals(612345L, shortLinkService.getShareId("2zix").longValue()); 60 | assertEquals(1234567L, shortLinkService.getShareId("5ban").longValue()); 61 | 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/util/FileSizeUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.util; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | /** 9 | * Created by pdwu on 2018/1/16. 10 | */ 11 | public class FileSizeUtilsTest { 12 | @Before 13 | public void setUp() throws Exception { 14 | } 15 | 16 | @Test 17 | public void getStringSize() throws Exception { 18 | 19 | String s = FileSizeUtils.getStringSize(1025); 20 | System.out.println(s); 21 | 22 | s = FileSizeUtils.getStringSize(100); 23 | System.out.println(s); 24 | 25 | s = FileSizeUtils.getStringSize(20490); 26 | System.out.println(s); 27 | 28 | s = FileSizeUtils.getStringSize(204900); 29 | System.out.println(s); 30 | 31 | s = FileSizeUtils.getStringSize(2049000); 32 | System.out.println(s); 33 | 34 | s = FileSizeUtils.getStringSize(6808055); 35 | System.out.println(s); 36 | 37 | s = FileSizeUtils.getStringSize(6808055000L); 38 | System.out.println(s); 39 | 40 | s = FileSizeUtils.getStringSize(6808055000000L); 41 | System.out.println(s); 42 | 43 | s = FileSizeUtils.getStringSize(6808055000000000L); 44 | System.out.println(s); 45 | 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/file/util/FileUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.file.util; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.springframework.mock.web.MockMultipartFile; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * Created by pdwu on 2017/12/19. 11 | */ 12 | public class FileUtilsTest { 13 | @Before 14 | public void setUp() throws Exception { 15 | } 16 | 17 | @Test 18 | public void getFileMD5() throws Exception { 19 | new FileUtils(); 20 | 21 | MockMultipartFile mockMultipartFile = new MockMultipartFile("data", "filename.txt", "text/plain", "thisIsContent".getBytes()); 22 | String res = FileUtils.getFileMD5(mockMultipartFile); 23 | assertEquals("f6c64c2816e3a17d19aae8fe1d709359", res); 24 | 25 | try { 26 | FileUtils.getFileMD5(null); 27 | fail(); //应有空指针异常 28 | } catch (Exception e) { 29 | 30 | } 31 | 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/user/dao/TokenDaoTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.dao; 2 | 3 | import com.ninja_squad.dbsetup.DbSetup; 4 | import com.ninja_squad.dbsetup.DbSetupTracker; 5 | import com.ninja_squad.dbsetup.Operations; 6 | import com.ninja_squad.dbsetup.destination.DataSourceDestination; 7 | import com.ninja_squad.dbsetup.operation.Operation; 8 | import com.pdwu.easycloud.user.bean.TokenBean; 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.test.context.ContextConfiguration; 14 | import org.springframework.test.context.TestPropertySource; 15 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 16 | import org.springframework.test.context.web.WebAppConfiguration; 17 | 18 | import javax.sql.DataSource; 19 | import java.util.Date; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | import java.util.Map; 23 | 24 | import static com.ninja_squad.dbsetup.Operations.sequenceOf; 25 | import static org.junit.Assert.*; 26 | 27 | /** 28 | * Created by pdwu on 2017/12/15. 29 | */ 30 | @RunWith(SpringJUnit4ClassRunner.class) 31 | @WebAppConfiguration("src/test/resources") 32 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml","classpath:spring/db-test.xml"}) 33 | public class TokenDaoTest { 34 | 35 | public static DbSetupTracker dbSetupTracker = new DbSetupTracker(); 36 | 37 | @Autowired 38 | private DataSource dataSource; 39 | 40 | @Autowired 41 | private TokenDao tokenDao; 42 | 43 | 44 | @Before 45 | public void setUp() throws Exception { 46 | Operation operation = sequenceOf( 47 | Operations.deleteAllFrom("user_info", "user_token"), 48 | Operations.insertInto("user_token") 49 | .columns("USER_ID", "TOKEN", "STATUS", "CREATE_TIME", "LAST_TIME") 50 | .values(10012L, "12d8aa790b4444aa9796c92cf8af28d9", 1, new Date(1513317967850L), new Date(1513317967860L)) 51 | .values(10012L, "13d8aa790b4444aa9796c92cf8af28d9", 0, new Date(1513317967860L), new Date(1513317967860L)) 52 | .values(10010L, "14d8aa790b4444aa9796c92cf8af28d9", 0, new Date(1513317967850L), new Date(1513317967850L)) 53 | .build() 54 | ); 55 | 56 | DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); 57 | dbSetupTracker.launchIfNecessary(dbSetup); 58 | } 59 | 60 | @Test 61 | public void selectToken() throws Exception { 62 | dbSetupTracker.skipNextLaunch(); 63 | 64 | Map param = new HashMap(); 65 | 66 | //token存在 67 | param.put("token", "12d8aa790b4444aa9796c92cf8af28d9"); 68 | List list1 = tokenDao.selectToken(param); 69 | assertEquals(10012L, list1.get(0).getUserId().longValue()); 70 | assertEquals("12d8aa790b4444aa9796c92cf8af28d9", list1.get(0).getToken()); 71 | assertEquals(1513317967850L, list1.get(0).getCreateTime().getTime()); 72 | 73 | //token不存在 74 | param.clear(); 75 | param.put("token", "xxxxaa790b4444aa9796c92cf8af2xxx"); 76 | List list2 = tokenDao.selectToken(param); 77 | assertEquals(0, list2.size()); 78 | 79 | //指定token和status,存在 80 | param.clear(); 81 | param.put("token", "13d8aa790b4444aa9796c92cf8af28d9"); 82 | param.put("status", 0); 83 | List list3 = tokenDao.selectToken(param); 84 | assertEquals(10012L, list3.get(0).getUserId().longValue()); 85 | 86 | 87 | //指定token和status,不存在 88 | param.clear(); 89 | param.put("token", "13d8aa790b4444aa9796c92cf8af28d9"); 90 | param.put("status", 1); 91 | List list4 = tokenDao.selectToken(param); 92 | assertEquals(0, list4.size()); 93 | 94 | //指定userId,存在(两条 10012L ) 95 | param.clear(); 96 | param.put("userId", 10012L); 97 | List list5 = tokenDao.selectToken(param); 98 | assertEquals(2, list5.size()); 99 | 100 | } 101 | 102 | @Test 103 | public void insertToken() throws Exception { 104 | 105 | TokenBean bean = new TokenBean(); 106 | bean.setCreateTime(new Date()); 107 | bean.setLastTime(new Date()); 108 | bean.setStatus(0); 109 | bean.setToken("123455790b4444aa9796c92cf8af2yyy"); 110 | bean.setUserId(10099L); 111 | 112 | int affectedRows = tokenDao.insertToken(bean); 113 | assertEquals(1, affectedRows); 114 | } 115 | 116 | @Test 117 | public void updateTokenStatus() throws Exception { 118 | 119 | Map param = new HashMap(); 120 | 121 | //token不存在 122 | param.put("token", "ooooooopxxx"); 123 | param.put("status", 1); 124 | int affectedRows = tokenDao.updateTokenStatus(param); 125 | assertEquals(0, affectedRows); 126 | 127 | //token存在 128 | param.clear(); 129 | param.put("token", "14d8aa790b4444aa9796c92cf8af28d9"); 130 | param.put("status", 1); 131 | int affectedRows2 = tokenDao.updateTokenStatus(param); 132 | assertEquals(1, affectedRows2); 133 | 134 | } 135 | 136 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/user/dao/UserDaoTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.dao; 2 | 3 | import com.ninja_squad.dbsetup.DbSetup; 4 | import com.ninja_squad.dbsetup.DbSetupTracker; 5 | import com.ninja_squad.dbsetup.Operations; 6 | import com.ninja_squad.dbsetup.destination.DataSourceDestination; 7 | import com.ninja_squad.dbsetup.operation.Operation; 8 | import com.pdwu.easycloud.user.bean.UserBean; 9 | import org.junit.Assert; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | import org.junit.runner.RunWith; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.test.context.ContextConfiguration; 15 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 16 | import org.springframework.test.context.web.WebAppConfiguration; 17 | 18 | import javax.sql.DataSource; 19 | 20 | import java.util.Date; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | import static com.ninja_squad.dbsetup.Operations.sequenceOf; 26 | import static org.junit.Assert.*; 27 | 28 | /** 29 | * Created by pdwu on 2017/12/15. 30 | */ 31 | @RunWith(SpringJUnit4ClassRunner.class) 32 | @WebAppConfiguration("src/main/resources") 33 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml","classpath:spring/db-test.xml"}) 34 | public class UserDaoTest { 35 | 36 | public static DbSetupTracker dbSetupTracker = new DbSetupTracker(); 37 | 38 | @Autowired 39 | private DataSource dataSource; 40 | 41 | @Autowired 42 | private UserDao userDao; 43 | 44 | @Before 45 | public void setUp() throws Exception { 46 | 47 | Operation operation = sequenceOf( 48 | Operations.deleteAllFrom("user_info", "user_token"), 49 | Operations.insertInto("user_info") 50 | .columns("USER_ID", "ACCOUNT", "PASSWORD", "CREATE_TIME", "LAST_TIME") 51 | .values(10010L, "xiaoming", "thisispassword", new Date(1513317967830L), new Date(1513317967830L)) 52 | .values(10011L, "zhangsan", "thisispassword", new Date(1513317967840L), new Date(1513317967840L)) 53 | .values(10012L, "lisi", "mythisispassword", new Date(1513317967850L), new Date(1513317967850L)) 54 | .build() 55 | ); 56 | 57 | DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); 58 | dbSetupTracker.launchIfNecessary(dbSetup); 59 | 60 | } 61 | 62 | @Test 63 | public void insertUser() throws Exception { 64 | 65 | UserBean bean = new UserBean(); 66 | bean.setAccount("testUser"); 67 | bean.setPassword("testInsertUserPsd"); 68 | bean.setLastTime(new Date(1513317967830L)); 69 | bean.setCreateTime(new Date(1513317967830L)); 70 | 71 | this.userDao.insertUser(bean); 72 | 73 | assertNotNull(bean.getUserId()); 74 | } 75 | 76 | @Test 77 | public void selectUserByAccountAndPassword() throws Exception { 78 | 79 | dbSetupTracker.skipNextLaunch(); 80 | 81 | //存在用户 密码正确 82 | UserBean param = new UserBean(); 83 | param.setAccount("xiaoming"); 84 | param.setPassword("thisispassword"); 85 | UserBean userBean = userDao.selectUserByAccountAndPassword(param); 86 | assertTrue(userBean.getAccount().equals("xiaoming")); 87 | assertEquals(null, userBean.getPassword()); 88 | assertEquals(1513317967830L, userBean.getCreateTime().getTime()); 89 | assertEquals(1513317967830L, userBean.getLastTime().getTime()); 90 | 91 | //存在用户,密码错误 92 | param.setPassword("xxx"); 93 | UserBean bean2 = userDao.selectUserByAccountAndPassword(param); 94 | assertNull(bean2); 95 | 96 | //用户不存在 97 | param.setAccount("xiaohong"); 98 | param.setPassword("sss"); 99 | UserBean bean3 = userDao.selectUserByAccountAndPassword(param); 100 | assertNull(bean3); 101 | } 102 | 103 | @Test 104 | public void selectUserAccountCount() throws Exception { 105 | dbSetupTracker.skipNextLaunch(); 106 | 107 | //有一个用户 108 | int count = this.userDao.selectUserAccountCount("xiaoming"); 109 | assertEquals(1, count); 110 | 111 | //不存在该用户 112 | int count2 = this.userDao.selectUserAccountCount("oop"); 113 | assertEquals(0, count2); 114 | 115 | } 116 | 117 | @Test 118 | public void selectUserInfo() throws Exception { 119 | 120 | //按userId找xiaoming 121 | Map param = new HashMap(); 122 | param.put("userId", "10010"); 123 | List list = this.userDao.selectUserInfo(param); 124 | assertEquals("xiaoming", list.get(0).getAccount()); 125 | 126 | //按account找zhangsan 127 | param.clear(); 128 | param.put("account", "zhangsan"); 129 | List list2 = this.userDao.selectUserInfo(param); 130 | assertEquals(10011L, list2.get(0).getUserId().longValue()); 131 | 132 | //不存在 userId 133 | param.clear(); 134 | param.put("userId", "10099"); 135 | List list3 = this.userDao.selectUserInfo(param); 136 | assertEquals(0, list3.size()); //返回空数组 137 | 138 | //按userId和account找 139 | param.clear(); 140 | param.put("userId", "10012"); 141 | param.put("account", "lisi"); 142 | List list4 = this.userDao.selectUserInfo(param); 143 | assertEquals(10012L, list4.get(0).getUserId().longValue()); 144 | assertEquals(1513317967850L, list4.get(0).getCreateTime().getTime()); 145 | } 146 | 147 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/user/service/impl/TokenServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.service.impl; 2 | 3 | import com.ninja_squad.dbsetup.DbSetup; 4 | import com.ninja_squad.dbsetup.DbSetupTracker; 5 | import com.ninja_squad.dbsetup.Operations; 6 | import com.ninja_squad.dbsetup.destination.DataSourceDestination; 7 | import com.ninja_squad.dbsetup.operation.Operation; 8 | import com.pdwu.easycloud.common.bean.ResultBean; 9 | import com.pdwu.easycloud.common.bean.ResultCode; 10 | import com.pdwu.easycloud.user.bean.TokenBean; 11 | import com.pdwu.easycloud.user.constant.TokenConstant; 12 | import com.pdwu.easycloud.user.service.ITokenService; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.test.context.ContextConfiguration; 18 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 19 | import org.springframework.test.context.web.WebAppConfiguration; 20 | 21 | import javax.sql.DataSource; 22 | 23 | import java.util.Date; 24 | 25 | import static com.ninja_squad.dbsetup.Operations.sequenceOf; 26 | import static org.junit.Assert.*; 27 | 28 | /** 29 | * Created by pdwu on 2017/12/16. 30 | */ 31 | @RunWith(SpringJUnit4ClassRunner.class) 32 | @WebAppConfiguration("src/main/resources") 33 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml","classpath:spring/db-test.xml"}) 34 | public class TokenServiceImplTest { 35 | 36 | 37 | public static DbSetupTracker dbSetupTracker = new DbSetupTracker(); 38 | 39 | @Autowired 40 | private DataSource dataSource; 41 | 42 | @Autowired 43 | private ITokenService tokenService; 44 | 45 | @Before 46 | public void setUp() throws Exception { 47 | 48 | Operation operation = sequenceOf( 49 | Operations.deleteAllFrom("user_info", "user_token"), 50 | Operations.insertInto("user_token") 51 | .columns("USER_ID", "TOKEN", "STATUS", "CREATE_TIME", "LAST_TIME") 52 | .values(10012L, "12d8aa790b4444aa9796c92cf8af28d9", 1, new Date(1513317967850L), new Date(1513317967860L)) 53 | .values(10012L, "13d8aa790b4444aa9796c92cf8af28d9", 0, new Date(1513317967860L), new Date(1513317967860L)) 54 | .values(10010L, "14d8aa790b4444aa9796c92cf8af28d9", 0, new Date(), new Date()) 55 | .values(10019L, "19d8aa790b4444aa9796c92cf8af28d9", 0, new Date(1513317967860L), new Date(1513317967860L)) 56 | .build() 57 | ); 58 | 59 | DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); 60 | dbSetupTracker.launchIfNecessary(dbSetup); 61 | 62 | } 63 | 64 | @Test 65 | public void addToken() throws Exception { 66 | 67 | TokenBean bean = tokenService.addToken(10055L); 68 | assertNotNull(bean.getCreateTime()); 69 | assertNotNull(bean.getLastTime()); 70 | assertNotNull(bean.getStatus()); 71 | assertNotNull(bean.getToken()); 72 | assertNotNull(bean.getUserId()); 73 | } 74 | 75 | @Test 76 | public void checkTokenValid() throws Exception { 77 | 78 | //参数校验 79 | assertEquals(400, tokenService.checkTokenValid(null).getCode()); 80 | 81 | //不存在的token 82 | assertEquals(1, tokenService.checkTokenValid("nothistoken").getCode()); 83 | 84 | //失效的token 85 | assertEquals(1, tokenService.checkTokenValid("12d8aa790b4444aa9796c92cf8af28d9").getCode()); 86 | 87 | //有效的token 10010L 88 | assertEquals(ResultCode.ok, tokenService.checkTokenValid("14d8aa790b4444aa9796c92cf8af28d9").getCode()); 89 | 90 | //数据库状态有效,但取出后再比较过期时间,会无效的token 10019L 91 | assertEquals(1, tokenService.checkTokenValid("19d8aa790b4444aa9796c92cf8af28d9").getCode()); 92 | 93 | 94 | } 95 | 96 | @Test 97 | public void updateTokenStatus() throws Exception { 98 | //参数 99 | assertEquals(400, tokenService.updateTokenStatus(null, 1).getCode()); 100 | 101 | //成功 102 | ResultBean bean = tokenService.updateTokenStatus("14d8aa790b4444aa9796c92cf8af28d9", TokenConstant.STATUS_DELETE); 103 | assertEquals(200, bean.getCode()); 104 | 105 | //状态已被更改 (还是会成功) 106 | ResultBean bean1 = tokenService.updateTokenStatus("12d8aa790b4444aa9796c92cf8af28d9", TokenConstant.STATUS_DELETE); 107 | assertEquals(200, bean1.getCode()); 108 | 109 | //token不存在 110 | ResultBean bean2 = tokenService.updateTokenStatus("faopsfjaf", TokenConstant.STATUS_DELETE); 111 | assertEquals(400, bean2.getCode()); 112 | 113 | } 114 | 115 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/user/service/impl/UserServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.service.impl; 2 | 3 | import com.ninja_squad.dbsetup.DbSetup; 4 | import com.ninja_squad.dbsetup.DbSetupTracker; 5 | import com.ninja_squad.dbsetup.Operations; 6 | import com.ninja_squad.dbsetup.destination.DataSourceDestination; 7 | import com.ninja_squad.dbsetup.operation.Operation; 8 | import com.pdwu.easycloud.common.bean.ResultBean; 9 | import com.pdwu.easycloud.common.bean.ResultCode; 10 | import com.pdwu.easycloud.user.bean.UserBean; 11 | import com.pdwu.easycloud.user.service.IUserService; 12 | import org.junit.Before; 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.test.context.ContextConfiguration; 17 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 18 | import org.springframework.test.context.web.WebAppConfiguration; 19 | 20 | import javax.sql.DataSource; 21 | 22 | import java.util.Date; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | import static com.ninja_squad.dbsetup.Operations.sequenceOf; 27 | import static org.junit.Assert.*; 28 | 29 | /** 30 | * Created by pdwu on 2017/12/16. 31 | */ 32 | @RunWith(SpringJUnit4ClassRunner.class) 33 | @WebAppConfiguration("src/main/resources") 34 | @ContextConfiguration(locations = {"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml","classpath:spring/db-test.xml"}) 35 | public class UserServiceImplTest { 36 | 37 | 38 | public static DbSetupTracker dbSetupTracker = new DbSetupTracker(); 39 | 40 | @Autowired 41 | private DataSource dataSource; 42 | 43 | @Autowired 44 | private IUserService userService; 45 | 46 | @Before 47 | public void setUp() throws Exception { 48 | 49 | //thisispassword md5: 81c93a6d22daaa5fdb4dbd4267e5e06e 50 | //mythisispassword md5: 28cc3ddb050d95a52aeb507bbd74c3e7 51 | 52 | Operation operation = sequenceOf( 53 | Operations.deleteAllFrom("user_info", "user_token"), 54 | Operations.insertInto("user_info") 55 | .columns("USER_ID", "ACCOUNT", "PASSWORD", "CREATE_TIME", "LAST_TIME") 56 | .values(10010L, "xiaoming", "81c93a6d22daaa5fdb4dbd4267e5e06e", new Date(1513317967830L), new Date(1513317967830L)) 57 | .values(10011L, "zhangsan", "81c93a6d22daaa5fdb4dbd4267e5e06e", new Date(1513317967840L), new Date(1513317967840L)) 58 | .values(10012L, "lisi", "28cc3ddb050d95a52aeb507bbd74c3e7", new Date(1513317967850L), new Date(1513317967850L)) 59 | .build(), 60 | Operations.insertInto("user_token") 61 | .columns("USER_ID", "TOKEN", "STATUS", "CREATE_TIME", "LAST_TIME") 62 | .values(10012L, "12d8aa790b4444aa9796c92cf8af28d9", 1, new Date(1513317967850L), new Date(1513317967860L)) 63 | .values(10012L, "13d8aa790b4444aa9796c92cf8af28d9", 0, new Date(1513317967860L), new Date(1513317967860L)) 64 | .values(10010L, "14d8aa790b4444aa9796c92cf8af28d9", 0, new Date(1513317967850L), new Date(1513317967850L)) 65 | .build() 66 | ); 67 | 68 | DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); 69 | dbSetupTracker.launchIfNecessary(dbSetup); 70 | 71 | } 72 | 73 | @Test 74 | public void login() throws Exception { 75 | 76 | dbSetupTracker.skipNextLaunch(); 77 | 78 | //参数校验 79 | assertNull(userService.login(null, null)); 80 | assertNull(userService.login("", null)); 81 | assertNull(userService.login("x", null)); 82 | 83 | //用户不存在 84 | UserBean bean = userService.login("nothisaccount", "mypassword"); 85 | assertNull(bean); 86 | 87 | //用户存在,密码不正确 88 | UserBean bean1 = userService.login("xiaoming", "errorpassword"); 89 | assertNull(bean1); 90 | 91 | //登录成功 92 | UserBean bean2 = userService.login("xiaoming", "thisispassword"); 93 | assertEquals(10010L, bean2.getUserId().longValue()); 94 | assertEquals(null, bean2.getPassword()); 95 | assertEquals(1513317967830L, bean2.getCreateTime().getTime()); 96 | assertNotNull(bean2.getToken()); //登录成功带上token 97 | 98 | } 99 | 100 | @Test 101 | public void register() throws Exception { 102 | 103 | //参数校验 104 | ResultBean bean = userService.register(null, null); 105 | assertEquals(ResultCode.fail, bean.getCode()); 106 | 107 | //注册成功 108 | ResultBean bean1 = userService.register("newUser", "mypasswordOOO"); 109 | assertEquals(ResultCode.ok, bean1.getCode()); 110 | 111 | //用户已存在 112 | ResultBean bean2 = userService.register("xiaoming", "xiaomingpassword"); 113 | assertEquals(ResultCode.fail, bean2.getCode()); 114 | 115 | 116 | } 117 | 118 | @Test 119 | public void getUserInfo() throws Exception { 120 | dbSetupTracker.skipNextLaunch(); 121 | 122 | //参数校验 123 | assertNull(userService.getUserInfo(null)); 124 | 125 | Map param = new HashMap(); 126 | 127 | //userId存在 128 | param.put("userId", 10010L); 129 | UserBean bean = userService.getUserInfo(param); 130 | assertEquals("xiaoming", bean.getAccount()); 131 | 132 | 133 | //account存在 134 | param.clear(); 135 | param.put("account", "zhangsan"); 136 | UserBean bean1 = userService.getUserInfo(param); 137 | assertEquals(10011L, bean1.getUserId().longValue()); 138 | 139 | //userId不存在 140 | param.clear(); 141 | param.put("userId", 9999L); 142 | UserBean bean2 = userService.getUserInfo(param); 143 | assertNull(null, bean2); 144 | 145 | } 146 | 147 | @Test 148 | public void logout() throws Exception { 149 | 150 | //参数 151 | assertEquals(400, userService.logout(null).getCode()); 152 | 153 | //不存在的token 154 | assertEquals(400, userService.logout("nothisToken").getCode()); 155 | 156 | //正常 157 | assertEquals(200, userService.logout("14d8aa790b4444aa9796c92cf8af28d9").getCode()); 158 | 159 | 160 | } 161 | 162 | } -------------------------------------------------------------------------------- /server/src/test/java/com/pdwu/easycloud/user/util/TokenUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.pdwu.easycloud.user.util; 2 | 3 | import com.pdwu.easycloud.user.bean.TokenBean; 4 | import com.pdwu.easycloud.user.constant.TokenConstant; 5 | import org.junit.Test; 6 | 7 | import java.util.Date; 8 | 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * Created by pdwu on 2017/12/16. 13 | */ 14 | public class TokenUtilsTest { 15 | @Test 16 | public void isOverDue() throws Exception { 17 | 18 | //参数校验 19 | assertTrue(TokenUtils.isOverDue(null)); 20 | assertTrue(TokenUtils.isOverDue(new TokenBean())); 21 | TokenBean t = new TokenBean(); 22 | t.setToken("tttoken"); 23 | t.setCreateTime(null); 24 | assertTrue(TokenUtils.isOverDue(t)); 25 | 26 | 27 | TokenBean bean = new TokenBean(); 28 | bean.setToken("oooo"); 29 | 30 | //新token,未过期 31 | bean.setCreateTime(new Date()); 32 | assertTrue(!TokenUtils.isOverDue(bean)); 33 | 34 | //2个时间段前的token,已过期 35 | long temp = System.currentTimeMillis() - 2 * (TokenConstant.OVERDUE_TIME_SECOND * 1000); 36 | bean.setCreateTime(new Date(temp)); 37 | assertTrue(TokenUtils.isOverDue(bean)); 38 | 39 | //半个时间段前的token,未过期 40 | long temp2 = System.currentTimeMillis() - (TokenConstant.OVERDUE_TIME_SECOND * 500); //0.5*1000=500 41 | bean.setCreateTime(new Date(temp2)); 42 | assertTrue(!TokenUtils.isOverDue(bean)); 43 | 44 | new TokenUtils(); 45 | new TokenConstant(); 46 | 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /web/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "modules": false, 5 | "targets": { 6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] 7 | } 8 | }], 9 | "stage-2" 10 | ], 11 | "plugins": ["transform-vue-jsx", "transform-runtime", 12 | ["component", [ 13 | { 14 | "libraryName": "element-ui", 15 | "styleLibraryName": "theme-chalk" 16 | } 17 | ]] 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /web/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /web/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | /dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Editor directories and files 9 | .idea 10 | .vscode 11 | *.suo 12 | *.ntvs* 13 | *.njsproj 14 | *.sln 15 | -------------------------------------------------------------------------------- /web/.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserslist" field in package.json 6 | "postcss-import": {}, 7 | "autoprefixer": {} 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /web/README.md: -------------------------------------------------------------------------------- 1 | # my-vue-project 2 | 3 | > A Vue.js project 4 | 5 | ## Build Setup 6 | 7 | ``` bash 8 | # install dependencies 9 | npm install 10 | 11 | # serve with hot reload at localhost:8080 12 | npm run dev 13 | 14 | # build for production with minification 15 | npm run build 16 | 17 | # build for production and view the bundle analyzer report 18 | npm run build --report 19 | ``` 20 | 21 | For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). 22 | -------------------------------------------------------------------------------- /web/build/build.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | require('./check-versions')() 3 | 4 | process.env.NODE_ENV = 'production' 5 | 6 | const ora = require('ora') 7 | const rm = require('rimraf') 8 | const path = require('path') 9 | const chalk = require('chalk') 10 | const webpack = require('webpack') 11 | const config = require('../config') 12 | const webpackConfig = require('./webpack.prod.conf') 13 | 14 | const spinner = ora('building for production...') 15 | spinner.start() 16 | 17 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 18 | if (err) throw err 19 | webpack(webpackConfig, (err, stats) => { 20 | spinner.stop() 21 | if (err) throw err 22 | process.stdout.write(stats.toString({ 23 | colors: true, 24 | modules: false, 25 | children: false, // if you are using ts-loader, setting this to true will make tyescript errors show up during build 26 | chunks: false, 27 | chunkModules: false 28 | }) + '\n\n') 29 | 30 | if (stats.hasErrors()) { 31 | console.log(chalk.red(' Build failed with errors.\n')) 32 | process.exit(1) 33 | } 34 | 35 | console.log(chalk.cyan(' Build complete.\n')) 36 | console.log(chalk.yellow( 37 | ' Tip: built files are meant to be served over an HTTP server.\n' + 38 | ' Opening index.html over file:// won\'t work.\n' 39 | )) 40 | }) 41 | }) 42 | -------------------------------------------------------------------------------- /web/build/check-versions.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const chalk = require('chalk') 3 | const semver = require('semver') 4 | const packageConfig = require('../package.json') 5 | const shell = require('shelljs') 6 | 7 | function exec (cmd) { 8 | return require('child_process').execSync(cmd).toString().trim() 9 | } 10 | 11 | const versionRequirements = [ 12 | { 13 | name: 'node', 14 | currentVersion: semver.clean(process.version), 15 | versionRequirement: packageConfig.engines.node 16 | } 17 | ] 18 | 19 | if (shell.which('npm')) { 20 | versionRequirements.push({ 21 | name: 'npm', 22 | currentVersion: exec('npm --version'), 23 | versionRequirement: packageConfig.engines.npm 24 | }) 25 | } 26 | 27 | module.exports = function () { 28 | const warnings = [] 29 | 30 | for (let i = 0; i < versionRequirements.length; i++) { 31 | const mod = versionRequirements[i] 32 | 33 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 34 | warnings.push(mod.name + ': ' + 35 | chalk.red(mod.currentVersion) + ' should be ' + 36 | chalk.green(mod.versionRequirement) 37 | ) 38 | } 39 | } 40 | 41 | if (warnings.length) { 42 | console.log('') 43 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 44 | console.log() 45 | 46 | for (let i = 0; i < warnings.length; i++) { 47 | const warning = warnings[i] 48 | console.log(' ' + warning) 49 | } 50 | 51 | console.log() 52 | process.exit(1) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /web/build/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/web/build/logo.png -------------------------------------------------------------------------------- /web/build/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const config = require('../config') 4 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 5 | const packageConfig = require('../package.json') 6 | 7 | exports.assetsPath = function (_path) { 8 | const assetsSubDirectory = process.env.NODE_ENV === 'production' 9 | ? config.build.assetsSubDirectory 10 | : config.dev.assetsSubDirectory 11 | 12 | return path.posix.join(assetsSubDirectory, _path) 13 | } 14 | 15 | exports.cssLoaders = function (options) { 16 | options = options || {} 17 | 18 | const cssLoader = { 19 | loader: 'css-loader', 20 | options: { 21 | sourceMap: options.sourceMap 22 | } 23 | } 24 | 25 | const postcssLoader = { 26 | loader: 'postcss-loader', 27 | options: { 28 | sourceMap: options.sourceMap 29 | } 30 | } 31 | 32 | // generate loader string to be used with extract text plugin 33 | function generateLoaders (loader, loaderOptions) { 34 | const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] 35 | 36 | if (loader) { 37 | loaders.push({ 38 | loader: loader + '-loader', 39 | options: Object.assign({}, loaderOptions, { 40 | sourceMap: options.sourceMap 41 | }) 42 | }) 43 | } 44 | 45 | // Extract CSS when that option is specified 46 | // (which is the case during production build) 47 | if (options.extract) { 48 | return ExtractTextPlugin.extract({ 49 | use: loaders, 50 | fallback: 'vue-style-loader' 51 | }) 52 | } else { 53 | return ['vue-style-loader'].concat(loaders) 54 | } 55 | } 56 | 57 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 58 | return { 59 | css: generateLoaders(), 60 | postcss: generateLoaders(), 61 | less: generateLoaders('less'), 62 | sass: generateLoaders('sass', { indentedSyntax: true }), 63 | scss: generateLoaders('sass'), 64 | stylus: generateLoaders('stylus'), 65 | styl: generateLoaders('stylus') 66 | } 67 | } 68 | 69 | // Generate loaders for standalone style files (outside of .vue) 70 | exports.styleLoaders = function (options) { 71 | const output = [] 72 | const loaders = exports.cssLoaders(options) 73 | 74 | for (const extension in loaders) { 75 | const loader = loaders[extension] 76 | output.push({ 77 | test: new RegExp('\\.' + extension + '$'), 78 | use: loader 79 | }) 80 | } 81 | 82 | return output 83 | } 84 | 85 | exports.createNotifierCallback = () => { 86 | const notifier = require('node-notifier') 87 | 88 | return (severity, errors) => { 89 | if (severity !== 'error') return 90 | 91 | const error = errors[0] 92 | const filename = error.file && error.file.split('!').pop() 93 | 94 | notifier.notify({ 95 | title: packageConfig.name, 96 | message: severity + ': ' + error.name, 97 | subtitle: filename || '', 98 | icon: path.join(__dirname, 'logo.png') 99 | }) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /web/build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const config = require('../config') 4 | const isProduction = process.env.NODE_ENV === 'production' 5 | const sourceMapEnabled = isProduction 6 | ? config.build.productionSourceMap 7 | : config.dev.cssSourceMap 8 | 9 | module.exports = { 10 | loaders: utils.cssLoaders({ 11 | sourceMap: sourceMapEnabled, 12 | extract: isProduction 13 | }), 14 | cssSourceMap: sourceMapEnabled, 15 | cacheBusting: config.dev.cacheBusting, 16 | transformToRequire: { 17 | video: ['src', 'poster'], 18 | source: 'src', 19 | img: 'src', 20 | image: 'xlink:href' 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /web/build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const config = require('../config') 5 | const vueLoaderConfig = require('./vue-loader.conf') 6 | 7 | function resolve (dir) { 8 | return path.join(__dirname, '..', dir) 9 | } 10 | 11 | 12 | 13 | module.exports = { 14 | context: path.resolve(__dirname, '../'), 15 | entry: { 16 | app: './src/main.js' 17 | }, 18 | output: { 19 | path: config.build.assetsRoot, 20 | filename: '[name].js', 21 | publicPath: process.env.NODE_ENV === 'production' 22 | ? config.build.assetsPublicPath 23 | : config.dev.assetsPublicPath 24 | }, 25 | resolve: { 26 | extensions: ['.js', '.vue', '.json'], 27 | alias: { 28 | 'vue$': 'vue/dist/vue.esm.js', 29 | '@': resolve('src'), 30 | } 31 | }, 32 | module: { 33 | rules: [ 34 | { 35 | test: /\.vue$/, 36 | loader: 'vue-loader', 37 | options: vueLoaderConfig 38 | }, 39 | { 40 | test: /\.js$/, 41 | loader: 'babel-loader', 42 | include: [resolve('src'), resolve('test')], 43 | options: { 44 | plugins: ['syntax-dynamic-import'] 45 | } 46 | }, 47 | { 48 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 49 | loader: 'url-loader', 50 | options: { 51 | limit: 10000, 52 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 53 | } 54 | }, 55 | { 56 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 57 | loader: 'url-loader', 58 | options: { 59 | limit: 10000, 60 | name: utils.assetsPath('media/[name].[hash:7].[ext]') 61 | } 62 | }, 63 | { 64 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 65 | loader: 'url-loader', 66 | options: { 67 | limit: 10000, 68 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 69 | } 70 | } 71 | ] 72 | }, 73 | node: { 74 | // prevent webpack from injecting useless setImmediate polyfill because Vue 75 | // source contains it (although only uses it if it's native). 76 | setImmediate: false, 77 | // prevent webpack from injecting mocks to Node native modules 78 | // that does not make sense for the client 79 | dgram: 'empty', 80 | fs: 'empty', 81 | net: 'empty', 82 | tls: 'empty', 83 | child_process: 'empty' 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /web/build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const webpack = require('webpack') 4 | const config = require('../config') 5 | const merge = require('webpack-merge') 6 | const baseWebpackConfig = require('./webpack.base.conf') 7 | const HtmlWebpackPlugin = require('html-webpack-plugin') 8 | const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 9 | const portfinder = require('portfinder') 10 | 11 | const HOST = process.env.HOST 12 | const PORT = process.env.PORT && Number(process.env.PORT) 13 | 14 | const devWebpackConfig = merge(baseWebpackConfig, { 15 | module: { 16 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) 17 | }, 18 | // cheap-module-eval-source-map is faster for development 19 | devtool: config.dev.devtool, 20 | 21 | // these devServer options should be customized in /config/index.js 22 | devServer: { 23 | clientLogLevel: 'warning', 24 | historyApiFallback: true, 25 | hot: true, 26 | compress: true, 27 | host: HOST || config.dev.host, 28 | port: PORT || config.dev.port, 29 | open: config.dev.autoOpenBrowser, 30 | overlay: config.dev.errorOverlay 31 | ? { warnings: false, errors: true } 32 | : false, 33 | publicPath: config.dev.assetsPublicPath, 34 | proxy: config.dev.proxyTable, 35 | quiet: true, // necessary for FriendlyErrorsPlugin 36 | watchOptions: { 37 | poll: config.dev.poll, 38 | } 39 | }, 40 | plugins: [ 41 | new webpack.DefinePlugin({ 42 | 'process.env': require('../config/dev.env') 43 | }), 44 | new webpack.HotModuleReplacementPlugin(), 45 | new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. 46 | new webpack.NoEmitOnErrorsPlugin(), 47 | // https://github.com/ampedandwired/html-webpack-plugin 48 | new HtmlWebpackPlugin({ 49 | filename: 'index.html', 50 | template: 'index.html', 51 | inject: true 52 | }), 53 | ] 54 | }) 55 | 56 | module.exports = new Promise((resolve, reject) => { 57 | portfinder.basePort = process.env.PORT || config.dev.port 58 | portfinder.getPort((err, port) => { 59 | if (err) { 60 | reject(err) 61 | } else { 62 | // publish the new Port, necessary for e2e tests 63 | process.env.PORT = port 64 | // add port to devServer config 65 | devWebpackConfig.devServer.port = port 66 | 67 | // Add FriendlyErrorsPlugin 68 | devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ 69 | compilationSuccessInfo: { 70 | messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], 71 | }, 72 | onErrors: config.dev.notifyOnErrors 73 | ? utils.createNotifierCallback() 74 | : undefined 75 | })) 76 | 77 | resolve(devWebpackConfig) 78 | } 79 | }) 80 | }) 81 | -------------------------------------------------------------------------------- /web/build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const webpack = require('webpack') 5 | const config = require('../config') 6 | const merge = require('webpack-merge') 7 | const baseWebpackConfig = require('./webpack.base.conf') 8 | const CopyWebpackPlugin = require('copy-webpack-plugin') 9 | const HtmlWebpackPlugin = require('html-webpack-plugin') 10 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 11 | const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 12 | const UglifyJsPlugin = require('uglifyjs-webpack-plugin') 13 | 14 | const env = require('../config/prod.env') 15 | 16 | const webpackConfig = merge(baseWebpackConfig, { 17 | module: { 18 | rules: utils.styleLoaders({ 19 | sourceMap: config.build.productionSourceMap, 20 | extract: true, 21 | usePostCSS: true 22 | }) 23 | }, 24 | devtool: config.build.productionSourceMap ? config.build.devtool : false, 25 | output: { 26 | path: config.build.assetsRoot, 27 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 28 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 29 | }, 30 | plugins: [ 31 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 32 | new webpack.DefinePlugin({ 33 | 'process.env': env 34 | }), 35 | new UglifyJsPlugin({ 36 | uglifyOptions: { 37 | compress: { 38 | warnings: false 39 | } 40 | }, 41 | sourceMap: config.build.productionSourceMap, 42 | parallel: true 43 | }), 44 | // extract css into its own file 45 | new ExtractTextPlugin({ 46 | filename: utils.assetsPath('css/[name].[contenthash].css'), 47 | // Setting the following option to `false` will not extract CSS from codesplit chunks. 48 | // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. 49 | // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 50 | // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 51 | allChunks: true, 52 | }), 53 | // Compress extracted CSS. We are using this plugin so that possible 54 | // duplicated CSS from different components can be deduped. 55 | new OptimizeCSSPlugin({ 56 | cssProcessorOptions: config.build.productionSourceMap 57 | ? { safe: true, map: { inline: false } } 58 | : { safe: true } 59 | }), 60 | // generate dist index.html with correct asset hash for caching. 61 | // you can customize output by editing /index.html 62 | // see https://github.com/ampedandwired/html-webpack-plugin 63 | new HtmlWebpackPlugin({ 64 | filename: config.build.index, 65 | template: 'index.html', 66 | inject: true, 67 | minify: { 68 | removeComments: true, 69 | collapseWhitespace: true, 70 | removeAttributeQuotes: true 71 | // more options: 72 | // https://github.com/kangax/html-minifier#options-quick-reference 73 | }, 74 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 75 | chunksSortMode: 'dependency' 76 | }), 77 | // keep module.id stable when vender modules does not change 78 | new webpack.HashedModuleIdsPlugin(), 79 | // enable scope hoisting 80 | new webpack.optimize.ModuleConcatenationPlugin(), 81 | // split vendor js into its own file 82 | new webpack.optimize.CommonsChunkPlugin({ 83 | name: 'vendor', 84 | minChunks (module) { 85 | // any required modules inside node_modules are extracted to vendor 86 | return ( 87 | module.resource && 88 | /\.js$/.test(module.resource) && 89 | module.resource.indexOf( 90 | path.join(__dirname, '../node_modules') 91 | ) === 0 92 | ) 93 | } 94 | }), 95 | // extract webpack runtime and module manifest to its own file in order to 96 | // prevent vendor hash from being updated whenever app bundle is updated 97 | new webpack.optimize.CommonsChunkPlugin({ 98 | name: 'manifest', 99 | minChunks: Infinity 100 | }), 101 | // This instance extracts shared chunks from code splitted chunks and bundles them 102 | // in a separate chunk, similar to the vendor chunk 103 | // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk 104 | new webpack.optimize.CommonsChunkPlugin({ 105 | name: 'app', 106 | async: 'vendor-async', 107 | children: true, 108 | minChunks: 3 109 | }), 110 | 111 | // copy custom static assets 112 | new CopyWebpackPlugin([ 113 | { 114 | from: path.resolve(__dirname, '../static'), 115 | to: config.build.assetsSubDirectory, 116 | ignore: ['.*'] 117 | } 118 | ]) 119 | ] 120 | }) 121 | 122 | if (config.build.productionGzip) { 123 | const CompressionWebpackPlugin = require('compression-webpack-plugin') 124 | 125 | webpackConfig.plugins.push( 126 | new CompressionWebpackPlugin({ 127 | asset: '[path].gz[query]', 128 | algorithm: 'gzip', 129 | test: new RegExp( 130 | '\\.(' + 131 | config.build.productionGzipExtensions.join('|') + 132 | ')$' 133 | ), 134 | threshold: 10240, 135 | minRatio: 0.8 136 | }) 137 | ) 138 | } 139 | 140 | if (config.build.bundleAnalyzerReport) { 141 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 142 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 143 | } 144 | 145 | module.exports = webpackConfig 146 | -------------------------------------------------------------------------------- /web/config/dev.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const merge = require('webpack-merge') 3 | const prodEnv = require('./prod.env') 4 | 5 | module.exports = merge(prodEnv, { 6 | NODE_ENV: '"development"' 7 | }) 8 | -------------------------------------------------------------------------------- /web/config/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | // Template version: 1.2.7 3 | // see http://vuejs-templates.github.io/webpack for documentation. 4 | 5 | const path = require('path') 6 | 7 | module.exports = { 8 | dev: { 9 | 10 | // Paths 11 | assetsSubDirectory: 'static', 12 | assetsPublicPath: '/', 13 | proxyTable: { 14 | '/api': { 15 | target: 'http://localhost:1088/api', 16 | changeOrigin: true, 17 | pathRewrite: { 18 | '^/api': '' 19 | } 20 | } 21 | }, 22 | 23 | // Various Dev Server settings 24 | host: 'localhost', // can be overwritten by process.env.HOST 25 | port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined 26 | autoOpenBrowser: false, 27 | errorOverlay: true, 28 | notifyOnErrors: true, 29 | poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- 30 | 31 | 32 | /** 33 | * Source Maps 34 | */ 35 | 36 | // https://webpack.js.org/configuration/devtool/#development 37 | devtool: 'eval-source-map', 38 | 39 | // If you have problems debugging vue-files in devtools, 40 | // set this to false - it *may* help 41 | // https://vue-loader.vuejs.org/en/options.html#cachebusting 42 | cacheBusting: true, 43 | 44 | // CSS Sourcemaps off by default because relative paths are "buggy" 45 | // with this option, according to the CSS-Loader README 46 | // (https://github.com/webpack/css-loader#sourcemaps) 47 | // In our experience, they generally work as expected, 48 | // just be aware of this issue when enabling this option. 49 | cssSourceMap: false, 50 | }, 51 | 52 | build: { 53 | // Template for index.html 54 | index: path.resolve(__dirname, '../dist/index.html'), 55 | 56 | // Paths 57 | assetsRoot: path.resolve(__dirname, '../dist'), 58 | assetsSubDirectory: 'static', 59 | assetsPublicPath: '/', 60 | 61 | /** 62 | * Source Maps 63 | */ 64 | 65 | productionSourceMap: true, 66 | // https://webpack.js.org/configuration/devtool/#production 67 | devtool: '#source-map', 68 | 69 | // Gzip off by default as many popular static hosts such as 70 | // Surge or Netlify already gzip all static assets for you. 71 | // Before setting to `true`, make sure to: 72 | // npm install --save-dev compression-webpack-plugin 73 | productionGzip: false, 74 | productionGzipExtensions: ['js', 'css'], 75 | 76 | // Run the build command with an extra argument to 77 | // View the bundle analyzer report after build finishes: 78 | // `npm run build --report` 79 | // Set to `true` or `false` to always turn it on or off 80 | bundleAnalyzerReport: process.env.npm_config_report 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /web/config/prod.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | module.exports = { 3 | NODE_ENV: '"production"' 4 | } 5 | -------------------------------------------------------------------------------- /web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | EasyCloud 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "EasyCloud-Web", 3 | "version": "1.0.0", 4 | "description": "A Vue.js project", 5 | "author": "oooop", 6 | "private": true, 7 | "scripts": { 8 | "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", 9 | "start": "npm run dev", 10 | "build": "node build/build.js", 11 | "analyz": "set NODE_ENV=production && set npm_config_report=true && npm run build" 12 | }, 13 | "dependencies": { 14 | "axios": "^0.17.1", 15 | "element-ui": "^2.0.8", 16 | "vue": "^2.5.2", 17 | "vue-router": "^3.0.1" 18 | }, 19 | "devDependencies": { 20 | "autoprefixer": "^7.1.2", 21 | "babel-core": "^6.22.1", 22 | "babel-helper-vue-jsx-merge-props": "^2.0.3", 23 | "babel-loader": "^7.1.1", 24 | "babel-plugin-component": "^1.0.0", 25 | "babel-plugin-syntax-jsx": "^6.18.0", 26 | "babel-plugin-transform-runtime": "^6.22.0", 27 | "babel-plugin-transform-vue-jsx": "^3.5.0", 28 | "babel-preset-env": "^1.3.2", 29 | "babel-preset-stage-2": "^6.22.0", 30 | "chalk": "^2.0.1", 31 | "copy-webpack-plugin": "^4.0.1", 32 | "css-loader": "^0.28.0", 33 | "extract-text-webpack-plugin": "^3.0.0", 34 | "file-loader": "^1.1.4", 35 | "friendly-errors-webpack-plugin": "^1.6.1", 36 | "html-webpack-plugin": "^2.30.1", 37 | "node-notifier": "^5.1.2", 38 | "optimize-css-assets-webpack-plugin": "^3.2.0", 39 | "ora": "^1.2.0", 40 | "portfinder": "^1.0.13", 41 | "postcss-import": "^11.0.0", 42 | "postcss-loader": "^2.0.8", 43 | "rimraf": "^2.6.0", 44 | "semver": "^5.3.0", 45 | "shelljs": "^0.7.6", 46 | "uglifyjs-webpack-plugin": "^1.1.1", 47 | "url-loader": "^0.5.8", 48 | "vue-loader": "^13.3.0", 49 | "vue-style-loader": "^3.0.1", 50 | "vue-template-compiler": "^2.5.2", 51 | "webpack": "^3.6.0", 52 | "webpack-bundle-analyzer": "^2.9.0", 53 | "webpack-dev-server": "^2.9.1", 54 | "webpack-merge": "^4.1.0" 55 | }, 56 | "engines": { 57 | "node": ">= 4.0.0", 58 | "npm": ">= 3.0.0" 59 | }, 60 | "browserslist": [ 61 | "> 1%", 62 | "last 2 versions", 63 | "not ie <= 8" 64 | ], 65 | "snippets": [ 66 | { 67 | "language": "javascript", 68 | "path": "./src/snippets/main.json" 69 | }, 70 | { 71 | "language": "typescript", 72 | "path": "./src/snippets/main.json" 73 | }, 74 | { 75 | "language": "html", 76 | "path": "./src/snippets/html.json" 77 | }, 78 | { 79 | "language": "vue", 80 | "path": "./src/snippets/main.json" 81 | }, 82 | { 83 | "language": "vue", 84 | "path": "./src/snippets/html.json" 85 | } 86 | ] 87 | } 88 | -------------------------------------------------------------------------------- /web/src/App.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 14 | 15 | 25 | -------------------------------------------------------------------------------- /web/src/components/AsideItem.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 20 | 31 | 32 | 35 | 36 | -------------------------------------------------------------------------------- /web/src/components/HeadItem.vue: -------------------------------------------------------------------------------- 1 | 24 | 25 | 26 | 72 | 73 | 92 | 93 | -------------------------------------------------------------------------------- /web/src/components/view/LoginView.vue: -------------------------------------------------------------------------------- 1 | 34 | 35 | 36 | 144 | 145 | 187 | 188 | -------------------------------------------------------------------------------- /web/src/components/view/MyShareView.vue: -------------------------------------------------------------------------------- 1 | 54 | 55 | 56 | 57 | 174 | 175 | 178 | 179 | -------------------------------------------------------------------------------- /web/src/components/view/NotFound.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 11 | 21 | 22 | 33 | 34 | -------------------------------------------------------------------------------- /web/src/components/view/PubShareView.vue: -------------------------------------------------------------------------------- 1 | 26 | 27 | 28 | 29 | 89 | 90 | 108 | 109 | -------------------------------------------------------------------------------- /web/src/components/view/RegisterView.vue: -------------------------------------------------------------------------------- 1 | 36 | 37 | 38 | 138 | 139 | 179 | 180 | -------------------------------------------------------------------------------- /web/src/main.js: -------------------------------------------------------------------------------- 1 | // The Vue build version to load with the `import` command 2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias. 3 | import Vue from 'vue' 4 | import App from './App' 5 | import router from './router' 6 | import axios from 'axios' 7 | //import ElementUI from 'element-ui' 8 | import 'element-ui/lib/theme-chalk/index.css' 9 | //Vue.use(ElementUI) 10 | 11 | import { Pagination,Button,ButtonGroup, Select,Dialog,Menu, Submenu, MenuItem, MenuItemGroup,Input, InputNumber,Table, 12 | TableColumn, Tooltip, Form, FormItem, Alert, Icon, Row, Col, Upload, Card, Progress,Container, Header, Aside, Main, Footer, 13 | Loading, MessageBox, Message, Notification} from 'element-ui' 14 | 15 | Vue.use(Pagination) 16 | Vue.use(Dialog) 17 | Vue.use(Menu) 18 | Vue.use(Submenu) 19 | Vue.use(MenuItem) 20 | Vue.use(MenuItemGroup) 21 | Vue.use(Input) 22 | Vue.use(InputNumber) 23 | Vue.use(Select) 24 | Vue.use(Button) 25 | Vue.use(ButtonGroup) 26 | Vue.use(Table) 27 | Vue.use(TableColumn) 28 | Vue.use(Tooltip) 29 | Vue.use(Form) 30 | Vue.use(FormItem) 31 | Vue.use(Alert) 32 | Vue.use(Icon) 33 | Vue.use(Row) 34 | Vue.use(Col) 35 | Vue.use(Upload) 36 | Vue.use(Card) 37 | Vue.use(Progress) 38 | Vue.use(Container) 39 | Vue.use(Header) 40 | Vue.use(Aside) 41 | Vue.use(Main) 42 | Vue.use(Footer) 43 | Vue.use(Loading.directive) 44 | 45 | //element ui 46 | Vue.prototype.$loading = Loading.service 47 | Vue.prototype.$msgbox = MessageBox 48 | Vue.prototype.$alert = MessageBox.alert 49 | Vue.prototype.$confirm = MessageBox.confirm 50 | Vue.prototype.$prompt = MessageBox.prompt 51 | Vue.prototype.$notify = Notification 52 | Vue.prototype.$message = Message 53 | 54 | Vue.config.productionTip = false 55 | Vue.prototype.$http = axios 56 | 57 | Vue.prototype.$user = { 58 | isLogin: function () { 59 | //1 for true, 0 false 60 | var v = localStorage.getItem("isLogin"); 61 | return v === "true" ? true : false; 62 | }, 63 | userId: function () { 64 | return localStorage.getItem("userId"); 65 | }, 66 | account: function () { 67 | return localStorage.getItem("account"); 68 | }, 69 | token: function () { 70 | return localStorage.getItem("token"); 71 | }, 72 | createTime: function () { 73 | return localStorage.getItem("createTime"); 74 | }, 75 | lastTime: function () { 76 | return localStorage.getItem("lastTime"); 77 | }, 78 | clean(){ 79 | localStorage.clear(); 80 | } 81 | } 82 | 83 | Vue.prototype.showErrorMsg = function (msg) { 84 | Vue.prototype.$message({ 85 | showClose: true, 86 | message: msg, 87 | type: 'error', 88 | duration: 3000 89 | }); 90 | } 91 | 92 | Vue.prototype.showSuccessMsg = function (msg) { 93 | Vue.prototype.$message({ 94 | showClose: true, 95 | duration: 3000, 96 | message: msg, 97 | type: 'success' 98 | }); 99 | } 100 | 101 | Vue.prototype.showInfoMsg = function (msg) { 102 | Vue.prototype.$message({ 103 | showClose: true, 104 | duration: 3000, 105 | message: msg, 106 | type: 'info' 107 | }); 108 | } 109 | 110 | function arraybuffer2str(buf) { 111 | var enc = new TextDecoder(); 112 | return enc.decode(buf); 113 | } 114 | 115 | 116 | axios.interceptors.response.use(function (response) { 117 | return response; 118 | }, function (error) { 119 | 120 | //统一处理token无效 121 | if (error.response.status === 401) { 122 | window.localStorage["isLogin"] = false; 123 | 124 | var toWhere = { 125 | name: 'route-login', 126 | params: { 127 | account: '' 128 | } 129 | }; 130 | 131 | if (Vue.prototype.$user.account() == undefined){ 132 | Vue.prototype.showErrorMsg('请先登录'); 133 | }else{ 134 | Vue.prototype.showErrorMsg('会话过期,请重新登录'); 135 | toWhere.params.account = Vue.prototype.$user.account(); 136 | } 137 | 138 | router.push(toWhere); 139 | 140 | } else { 141 | 142 | if (error.config.responseType === "arraybuffer") { 143 | //下载文件返回错误 144 | var str = arraybuffer2str(error.response.data); 145 | var obj = JSON.parse(str); 146 | Vue.prototype.showErrorMsg(obj.msg); 147 | return; 148 | } 149 | 150 | //存在服务端返回的msg则显示msg 151 | if (error.response.data.msg) { 152 | Vue.prototype.showErrorMsg(error.response.data.msg); 153 | } else { 154 | //否则展示状态码 155 | var pre = ''; 156 | if (error.response.status >= 500){ 157 | pre = '服务异常,请刷新重试!'; 158 | } 159 | Vue.prototype.showErrorMsg(pre + error.response.status + " " + error.response.statusText) 160 | } 161 | } 162 | 163 | //Promise.resolve(error.response) 164 | return new Promise(() => {}); 165 | }); 166 | 167 | 168 | /* eslint-disable no-new */ 169 | new Vue({ 170 | el: '#app', 171 | router, 172 | template: '', 173 | components: { 174 | App 175 | } 176 | }) 177 | -------------------------------------------------------------------------------- /web/src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | 4 | import HeadItem from '@/components/HeadItem' 5 | import AsideItem from '@/components/AsideItem' 6 | const LoginView = () => import('@/components/view/LoginView.vue') 7 | const MyShareView = () => import('@/components/view/MyShareView.vue') 8 | const RegisterView = () => import('@/components/view/RegisterView.vue') 9 | const NotFound = () => import('@/components/view/NotFound.vue') 10 | const MyFileView = () => import('@/components/view/MyFileView.vue') 11 | const PubShareView = () => import('@/components/view/PubShareView.vue') 12 | 13 | Vue.use(Router) 14 | 15 | export default new Router({ 16 | mode: 'history', 17 | routes: [ 18 | { 19 | path: '/', 20 | name: 'route-index', 21 | component: MyFileView 22 | }, 23 | { 24 | path: '/myshare', 25 | name: 'route-my-share', 26 | component: MyShareView 27 | }, 28 | { 29 | path: '/login', 30 | name: 'route-login', 31 | component: LoginView 32 | }, 33 | { 34 | path: '/register', 35 | name: 'route-register', 36 | component: RegisterView 37 | 38 | }, 39 | { 40 | path: '/share/:code', 41 | name: 'route-pub-share', 42 | component: PubShareView 43 | }, 44 | { 45 | path: '*', 46 | name: '404', 47 | component: NotFound 48 | } 49 | ] 50 | }) 51 | -------------------------------------------------------------------------------- /web/static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zilw/EasyCloud/bdfdc7848b8fc435e0c57534c11e8534fe85467e/web/static/.gitkeep --------------------------------------------------------------------------------