From 3d3f9e79188ce8f4fc2a5856bdbdd9944ad9deac Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Tue, 17 Aug 2021 12:26:25 +0800 Subject: [PATCH 01/13] =?UTF-8?q?=E5=AE=8C=E6=88=90=E7=9B=B4=E6=92=AD?= =?UTF-8?q?=E9=97=B4=E5=8D=B3=E6=97=B6=E9=80=9A=E4=BF=A1=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 6 + .../com/zgn/fazhi/config/ShiroConfig.java | 2 +- .../com/zgn/fazhi/config/WebSocketConfig.java | 16 +++ .../zgn/fazhi/controller/LoginController.java | 3 +- .../service/impl/UserInfoServiceImpl.java | 4 - .../zgn/fazhi/ws/GetUserInfoConfigurator.java | 23 ++++ .../java/com/zgn/fazhi/ws/LiveEndopint.java | 130 ++++++++++++++++++ src/main/resources/application-dev.properties | 2 +- .../resources/application-prod.properties | 2 +- 9 files changed, 180 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/zgn/fazhi/config/WebSocketConfig.java create mode 100644 src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java create mode 100644 src/main/java/com/zgn/fazhi/ws/LiveEndopint.java diff --git a/pom.xml b/pom.xml index 943feec..cd23c3a 100644 --- a/pom.xml +++ b/pom.xml @@ -62,6 +62,12 @@ 3.13.0 + + + org.springframework.boot + spring-boot-starter-websocket + + com.aliyun diff --git a/src/main/java/com/zgn/fazhi/config/ShiroConfig.java b/src/main/java/com/zgn/fazhi/config/ShiroConfig.java index 5cfb607..4e58b13 100644 --- a/src/main/java/com/zgn/fazhi/config/ShiroConfig.java +++ b/src/main/java/com/zgn/fazhi/config/ShiroConfig.java @@ -107,7 +107,7 @@ public class ShiroConfig { filterChainDefinitionMap.put("/api/register", "anon"); filterChainDefinitionMap.put("/api/login", "anon"); filterChainDefinitionMap.put("/api/logout", "logout"); - filterChainDefinitionMap.put("/**", "jwtFilter,authc"); +// filterChainDefinitionMap.put("/**", "jwtFilter,authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } diff --git a/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java b/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java new file mode 100644 index 0000000..2e498e5 --- /dev/null +++ b/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java @@ -0,0 +1,16 @@ +package com.zgn.fazhi.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; + +@Configuration +public class WebSocketConfig { + + /** 扫描注解了@ServerEndpoint注解的类 */ + @Bean + public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); + } + +} diff --git a/src/main/java/com/zgn/fazhi/controller/LoginController.java b/src/main/java/com/zgn/fazhi/controller/LoginController.java index 193140b..f0136c2 100644 --- a/src/main/java/com/zgn/fazhi/controller/LoginController.java +++ b/src/main/java/com/zgn/fazhi/controller/LoginController.java @@ -26,7 +26,8 @@ public class LoginController { @PostMapping(value = "/api/login") public Result userLogin(@RequestParam("username") String username, @RequestParam("password") String password, ServletResponse response) { - + log.info("用户名: {}", username); + log.info("密码: {}", password); // 获取当前用户主体 Subject subject = SecurityUtils.getSubject(); String msg = null; diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java index 5baa717..586a242 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java @@ -283,17 +283,13 @@ public class UserInfoServiceImpl extends ServiceImpl i try { // 先查询缓存,缓存没有则查询数据库返回 if (redisUtil.hasKey(KEY + uid)) { - log.info("当前缓存有该用户"); UserInfo userInfo = FastJsonUtils.toBean(redisUtil.get(KEY + uid), UserInfo.class);; - log.info("当前缓存用户为: {}", userInfo); return userInfo; } else { - log.info("缓存没有该用户"); return selectPutCache(uid); } } catch (RedisConnectionFailureException e) { e.printStackTrace(); - log.error("redis连接错误"); return userMapper.selectById(uid); } } diff --git a/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java b/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java new file mode 100644 index 0000000..c5c986d --- /dev/null +++ b/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java @@ -0,0 +1,23 @@ +package com.zgn.fazhi.ws; + +import com.zgn.fazhi.utils.JwtUtils; +import lombok.extern.slf4j.Slf4j; + +import javax.websocket.HandshakeResponse; +import javax.websocket.server.HandshakeRequest; +import javax.websocket.server.ServerEndpointConfig; +import java.util.Map; + +@Slf4j +public class GetUserInfoConfigurator extends ServerEndpointConfig.Configurator { + + @Override + public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { + // 获取请求头 token + try { + String token = request.getHeaders().get(JwtUtils.AUTH_HEADER).get(0); + Map userProperties = sec.getUserProperties(); + userProperties.put("token", token); + } catch (NullPointerException ignored){} + } +} diff --git a/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java b/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java new file mode 100644 index 0000000..450c3fc --- /dev/null +++ b/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java @@ -0,0 +1,130 @@ +package com.zgn.fazhi.ws; + +import com.zgn.fazhi.service.UserInfoService; +import com.zgn.fazhi.utils.JwtUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 直播间即时通信 websoket + */ +@Slf4j +@Component +@ServerEndpoint(value = "/ws/live/{roomId}", configurator = GetUserInfoConfigurator.class) +public class LiveEndopint { + + /** + * 使用map来收集session,key为roomName,value为同一个房间的用户集合 + * concurrentMap的key不存在时报错,不是返回null + */ + private static final Map> ROOMS = new ConcurrentHashMap(); + + /** + * 用来给客户端发送消息 + */ + private Session session; + + /** + * 存放当前用户名 + */ + private String name; + + private static UserInfoService userInfoService; + + @Autowired + public void setUserInfoService(UserInfoService userInfoService){ + LiveEndopint.userInfoService = userInfoService; + } + + /** + * 建立连接触发事件 + * + * @param roomId 房间id + * @param session 用户session + */ + @OnOpen + public void connect(@PathParam("roomId") String roomId, Session session, EndpointConfig endpointConfig) throws Exception { + try { + this.name = userInfoService.findByUid( + JwtUtils.getUidByToken( + endpointConfig + .getUserProperties() + .get("token") + .toString())) + .getName(); + } catch (NullPointerException ignored){} + this.session = session; + + // 将session按照房间名来存储,将各个房间的用户隔离 + if (!ROOMS.containsKey(roomId)) { + // 创建房间不存在时,创建房间 + Set room = new HashSet<>(); + // 添加用户 + room.add(session); + ROOMS.put(roomId, room); + } else { + // 房间已存在,直接添加用户到相应的房间 + ROOMS.get(roomId).add(session); + } + String msg = "用户" + name + "进入房间"; + // 对该房间进行广播 + broadcast(roomId, msg); + log.info(msg); + } + + /** + * 客户端断开连接 + * + * @param roomId 房间id + * @param session 用户session + */ + @OnClose + public void disConnect(@PathParam("roomId") String roomId, Session session) { + ROOMS.get(roomId).remove(session); + System.out.println("a client has disconnected!"); + } + + + /** + * 用户推送信息到直播间 + * + * @param roomId 房间id + * @param msg 消息 + * @param session 用户session + */ + @OnMessage + public void receiveMsg(@PathParam("roomId") String roomId, String msg, Session session) { + // 此处应该有html过滤 + msg = name + ":" + msg; + log.info("向房间号:{}推送消息:{}", roomId, msg); + // 接收到信息后进行广播 + try { + broadcast(roomId, msg); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 按照房间id进行广播 + * + * @param roomId 房间id + * @param msg 消息 + * @throws Exception + */ + public static void broadcast(String roomId, String msg) throws Exception { + for (Session session : ROOMS.get(roomId)) { + session.getBasicRemote().sendText(msg); + } + } + +} diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index c828bcb..083c200 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -3,4 +3,4 @@ server.port=8083 spring.datasource.url=jdbc:mysql://localhost:3306/fazhi?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true # ���ݿ��û���&���룺 spring.datasource.username=root -spring.datasource.password=root +spring.datasource.password=zgn12.21 diff --git a/src/main/resources/application-prod.properties b/src/main/resources/application-prod.properties index cd96c8a..4b790f6 100644 --- a/src/main/resources/application-prod.properties +++ b/src/main/resources/application-prod.properties @@ -3,4 +3,4 @@ server.port=8088 spring.datasource.url=jdbc:mysql://localhost:3306/books?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT # ݿû&룺 spring.datasource.username=root -spring.datasource.password=CHENzijia12300 \ No newline at end of file +spring.datasource.password=root \ No newline at end of file -- Gitee From d83678663af0696c43be98c9593f188bf2b662de Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Wed, 18 Aug 2021 01:44:35 +0800 Subject: [PATCH 02/13] =?UTF-8?q?=E5=AE=8C=E6=88=90=E7=9B=B4=E6=92=AD?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/zgn/fazhi/config/ShiroConfig.java | 5 +- .../controller/AliYunLiveController.java | 52 ++++++-- .../controller/AppointmentController.java | 2 +- .../com/zgn/fazhi/mapper/LiveInfoMapper.java | 30 +++++ .../java/com/zgn/fazhi/pojo/po/LiveInfo.java | 48 +++++++ .../com/zgn/fazhi/pojo/vo/UserLiveInfo.java | 35 ++++++ .../zgn/fazhi/service/AliYunLiveService.java | 43 +++++++ .../service/impl/AliYunLivServiceImpl.java | 119 +++++++++++++++++- .../com/zgn/fazhi/utils/AliYunLiveUtil.java | 73 ++++++----- .../java/com/zgn/fazhi/ws/LiveEndopint.java | 3 +- src/test/java/com/zgn/fazhi/Test2.java | 10 +- 11 files changed, 366 insertions(+), 54 deletions(-) create mode 100644 src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java create mode 100644 src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java create mode 100644 src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java diff --git a/src/main/java/com/zgn/fazhi/config/ShiroConfig.java b/src/main/java/com/zgn/fazhi/config/ShiroConfig.java index 4e58b13..bdd5c94 100644 --- a/src/main/java/com/zgn/fazhi/config/ShiroConfig.java +++ b/src/main/java/com/zgn/fazhi/config/ShiroConfig.java @@ -104,10 +104,13 @@ public class ShiroConfig { filterChainDefinitionMap.put("/configuration/**", "anon"); filterChainDefinitionMap.put("/static/**", "anon"); + // 阿里云直播回调 + filterChainDefinitionMap.put("/api/aliyunLive", "anon"); + filterChainDefinitionMap.put("/api/register", "anon"); filterChainDefinitionMap.put("/api/login", "anon"); filterChainDefinitionMap.put("/api/logout", "logout"); -// filterChainDefinitionMap.put("/**", "jwtFilter,authc"); + filterChainDefinitionMap.put("/**", "jwtFilter,authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } diff --git a/src/main/java/com/zgn/fazhi/controller/AliYunLiveController.java b/src/main/java/com/zgn/fazhi/controller/AliYunLiveController.java index d6f8894..a2c24f7 100644 --- a/src/main/java/com/zgn/fazhi/controller/AliYunLiveController.java +++ b/src/main/java/com/zgn/fazhi/controller/AliYunLiveController.java @@ -1,17 +1,22 @@ package com.zgn.fazhi.controller; +import com.zgn.fazhi.factory.ResultFactory; +import com.zgn.fazhi.pojo.po.LiveInfo; import com.zgn.fazhi.pojo.vo.ApiLiveModel; import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.AliYunLiveService; import com.zgn.fazhi.utils.FastJsonUtils; +import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; @Api(tags = "阿里云直播接口") @RestController @@ -21,15 +26,38 @@ public class AliYunLiveController { @Autowired private AliYunLiveService aliYunLiveService; - /** - * 生成推流播流地址 - * @param sourceId 房间号 - * @return - */ - @GetMapping("/api/saveLive") - public Result saveLive(@RequestParam("sourceId") String sourceId){ - aliYunLiveService.saveLive(sourceId); - return null; + @ApiOperation("获取直播间信息") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) + @GetMapping("/api/getLiveInfo") + public Result getLiveInfo(@RequestHeader(JwtUtils.AUTH_HEADER) String token){ + return ResultFactory.buildSuccessResult(aliYunLiveService.getLiveInfo(JwtUtils.getUidByToken(token))); + } + + @ApiOperation("更新直播间信息") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) + @PostMapping("/api/updateLiveInfo") + public Result updateLiveInfo(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @Valid @RequestBody LiveInfo liveInfo){ + aliYunLiveService.updateLiveInfo(liveInfo, JwtUtils.getUidByToken(token)); + return ResultFactory.buildSuccessResult("更新成功"); + } + + @ApiOperation("开启直播,获取推流url") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) + @PostMapping("/api/startLive") + public Result startLive(@RequestHeader(JwtUtils.AUTH_HEADER) String token){ + return ResultFactory.buildSuccessResult(aliYunLiveService.startLive(JwtUtils.getUidByToken(token))); + } + + @ApiOperation("获取正在开播的直播") + @GetMapping("/api/getAllLive") + public Result getAllLive(){ + return ResultFactory.buildSuccessResult(aliYunLiveService.getAllLiveIfOn()); + } + + @ApiOperation("通过房间号获取播流url") + @GetMapping("/api/getLiveByRoomId/{id}") + public Result getLiveByRoomId(@PathVariable Integer id){ + return ResultFactory.buildSuccessResult(aliYunLiveService.getPullUrl(id)); } /** diff --git a/src/main/java/com/zgn/fazhi/controller/AppointmentController.java b/src/main/java/com/zgn/fazhi/controller/AppointmentController.java index 02517fc..5d0d19b 100644 --- a/src/main/java/com/zgn/fazhi/controller/AppointmentController.java +++ b/src/main/java/com/zgn/fazhi/controller/AppointmentController.java @@ -44,7 +44,7 @@ public class AppointmentController { @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @ApiOperation("获取某一天的预约情况") @PostMapping("/api/getAppointmentInfo") - public Result getAppointmentInfo(@RequestBody String date) throws ParseException { + public Result getAppointmentInfo(@RequestBody String date) { // 通过日期查询当天的预约情况 return ResultFactory.buildSuccessResult(appointmentService.getAppointmentByDate(date)); } diff --git a/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java b/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java new file mode 100644 index 0000000..fd1abca --- /dev/null +++ b/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java @@ -0,0 +1,30 @@ +package com.zgn.fazhi.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.zgn.fazhi.pojo.po.LiveInfo; +import com.zgn.fazhi.pojo.vo.UserLiveInfo; +import org.apache.ibatis.annotations.Select; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @author ydw + * @version 1.0 + * @Description TODO + * @date 17/08/2021 9:18 PM + */ + +@Repository +public interface LiveInfoMapper extends BaseMapper { + + /** + * 查询所有直播间 + * + * @return 所有直播间信息 + */ + @Select("SELECT l.id, u.name, title, info, if_live " + + "FROM live_info AS l INNER JOIN user_info AS u ON l.uid = u.id") + List getAllLive(); + +} diff --git a/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java b/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java new file mode 100644 index 0000000..a301040 --- /dev/null +++ b/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java @@ -0,0 +1,48 @@ +package com.zgn.fazhi.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Date; + +/** + * @author ydw + * @version 1.0 + * @description 直播间信息 + * @date 17/08/2021 8:08 PM + */ + +@Data +@Accessors(chain = true) +@ApiModel("直播信息实体类") +public class LiveInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "房间id不能为空") + @ApiModelProperty("直播房间号id") + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + + @ApiModelProperty("主播id") + private Integer uid; + + @ApiModelProperty("直播间标题") + private String title; + + @ApiModelProperty("直播简介") + private String info; + + @ApiModelProperty("是否直播中") + private Integer ifLive; + + @ApiModelProperty("最后一次直播时间") + private Date lastLive; + +} diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java b/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java new file mode 100644 index 0000000..4f395dd --- /dev/null +++ b/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java @@ -0,0 +1,35 @@ +package com.zgn.fazhi.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author ydw + * @version 1.0 + * @description 直播间基础信息 + * @date 17/08/2021 11:10 PM + */ + +@Data +public class UserLiveInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("房间号") + private Integer id; + + @ApiModelProperty("主播名") + private String name; + + @ApiModelProperty("直播标题") + private String title; + + @ApiModelProperty("直播简介") + private String info; + + @ApiModelProperty("是否正在直播") + private Integer ifLive; + +} diff --git a/src/main/java/com/zgn/fazhi/service/AliYunLiveService.java b/src/main/java/com/zgn/fazhi/service/AliYunLiveService.java index af31829..cca775c 100644 --- a/src/main/java/com/zgn/fazhi/service/AliYunLiveService.java +++ b/src/main/java/com/zgn/fazhi/service/AliYunLiveService.java @@ -1,8 +1,11 @@ package com.zgn.fazhi.service; +import com.zgn.fazhi.pojo.po.LiveInfo; import com.zgn.fazhi.pojo.vo.ApiLiveModel; +import com.zgn.fazhi.pojo.vo.UserLiveInfo; +import java.util.List; import java.util.Map; public interface AliYunLiveService { @@ -19,4 +22,44 @@ public interface AliYunLiveService { */ void saveLive(String sourceId); + /** + * 获取直播间信息 + * @param uid 用户id + * @return 该用户的直播间信息 + */ + LiveInfo getLiveInfo(Integer uid); + + /** + * 开启直播,获取推流url + * @param uid 用户id + * @return 推流url + */ + String startLive(Integer uid); + + /** + * 更新直播间信息 + * @param liveInfo 、直播间信息 + * @return + */ + Boolean updateLiveInfo(LiveInfo liveInfo, Integer currentUserId); + + /** + * 获取所有正在直播的直播间 + * @return + */ + List getAllLiveIfOn(); + + /** + * 获取所有直播 + * @return + */ + List getAllLive(); + + /** + * 根据房间号获取播流url + * @param lId 房间号 + * @return rtmp类型的播流url + */ + String getPullUrl(Integer lId); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java index 100b578..3a20f77 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java @@ -1,12 +1,25 @@ package com.zgn.fazhi.service.impl; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.zgn.fazhi.config.AliYunLiveConfig; +import com.zgn.fazhi.exception.RestException; +import com.zgn.fazhi.mapper.LiveInfoMapper; +import com.zgn.fazhi.pojo.po.LiveInfo; import com.zgn.fazhi.pojo.vo.ApiLiveModel; +import com.zgn.fazhi.pojo.vo.UserLiveInfo; import com.zgn.fazhi.service.AliYunLiveService; import com.zgn.fazhi.utils.AliYunLiveUtil; +import com.zgn.fazhi.utils.FastJsonUtils; +import com.zgn.fazhi.utils.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.stream.Collectors; @Service @Slf4j @@ -22,9 +35,17 @@ public class AliYunLivServiceImpl implements AliYunLiveService { */ private static final String CUTOFF = "publish_done"; + @Autowired + private LiveInfoMapper liveInfoMapper; + @Autowired private AliYunLiveConfig aliyunConfig; + @Autowired + private RedisUtil redisUtil; + + private static final String KEY = "onLiveKey"; + @Override public void aliyunLiveCallback(ApiLiveModel model) { try { @@ -33,17 +54,25 @@ public class AliYunLivServiceImpl implements AliYunLiveService { //获取直播状态值 String action = model.getAction().get(0); //获取直播房间号 - String houseId = model.getId().get(0); + Integer houseId = Integer.parseInt(model.getId().get(0)); if (PUSH.equals(action)) { log.info("开启直播状态,房间号: {}", houseId); - //业务处理 + // 标记该直播间为开播状态 + liveInfoMapper.updateById( + new LiveInfo().setId(houseId) + .setIfLive(1)); + redisUtil.del(KEY); } else if (CUTOFF.equals(action)) { log.info("关闭直播状态,房间号: {}", houseId); - //业务处理 + // 标记该直播间为下播状态 + liveInfoMapper.updateById( + new LiveInfo().setId(houseId) + .setIfLive(0)); + redisUtil.del(KEY); } } - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } @@ -56,11 +85,91 @@ public class AliYunLivServiceImpl implements AliYunLiveService { log.info("生成推流地址: {}", pushUrl); //生成播流地址 - String pullUrl = AliYunLiveUtil.createPullUrl(sourceId, aliyunConfig); + String pullUrl = AliYunLiveUtil.createPullUrl(sourceId, aliyunConfig,3); log.info("生成播流地址: {}", pullUrl); } catch (Exception e) { e.printStackTrace(); } } + + @Override + public LiveInfo getLiveInfo(Integer uid) { + LiveInfo liveInfo = liveInfoMapper.selectOne(new QueryWrapper().eq("uid", uid)); + // 查询数据库判断是否第一次直播, 如果不是则返回上次直播间信息, 是则返回null + if (StringUtils.isEmpty(liveInfo)) { + // 如果为空,则为该用户新建直播间,并返回 + liveInfo = new LiveInfo().setUid(uid); + liveInfoMapper.insert(liveInfo); + } + return liveInfo; + } + + @Override + public String startLive(Integer uid) { + // 通过uid获取直播间id + Integer roomId = liveInfoMapper.selectOne(new QueryWrapper().eq("uid", uid)).getId(); + if (StringUtils.isEmpty(roomId)) { + throw new RestException(400, "初始化直播间失败"); + } + // 根据房间id生成推流地址 + return AliYunLiveUtil.createPushUrl(roomId.toString(), aliyunConfig); + } + + @Override + public Boolean updateLiveInfo(LiveInfo liveInfo, Integer currentUserId) { + // 获取当前用户的直播间id,更新信息 + liveInfoMapper.updateById( + liveInfo.setIfLive(null) + .setUid(null) + .setLastLive(null) + .setId(liveInfoMapper.selectOne( + new QueryWrapper() + .eq("uid", currentUserId)) + .getId())); + redisUtil.del(KEY); + return true; + } + + @Override + public List getAllLiveIfOn() { + try { + if (redisUtil.hasKey(KEY)) { + return FastJsonUtils.toList(redisUtil.get(KEY), UserLiveInfo.class); + } + } catch (RedisConnectionFailureException e) { + return getOnLive(); + } + List onLive = getOnLive(); + redisUtil.setIfAbsent(KEY, onLive, RedisUtil.EXPIRETIME); + return onLive; + } + + @Override + public List getAllLive() { + return liveInfoMapper.getAllLive(); + } + + private List getOnLive() { + return getAllLive().stream().filter(liveInfo -> liveInfo.getIfLive() == 1).collect(Collectors.toList()); + } + + @Override + public String getPullUrl(Integer lId) { + String key = KEY + ":" + lId; + // 查询缓存 + try { + if (redisUtil.hasKey(key)) { + return redisUtil.get(key).toString(); + } + } catch (RedisConnectionFailureException e){ + return AliYunLiveUtil.createPullUrl(lId.toString(), aliyunConfig, 3); + } + // 微信小程序直播只支持rtmp + String pullUrl = AliYunLiveUtil.createPullUrl(lId.toString(), aliyunConfig, 3); + // 有效期设置29分钟 + redisUtil.setIfAbsent(key, pullUrl, 60 * 29); + // 生成播流地址 + return pullUrl; + } } diff --git a/src/main/java/com/zgn/fazhi/utils/AliYunLiveUtil.java b/src/main/java/com/zgn/fazhi/utils/AliYunLiveUtil.java index b250929..25d2052 100644 --- a/src/main/java/com/zgn/fazhi/utils/AliYunLiveUtil.java +++ b/src/main/java/com/zgn/fazhi/utils/AliYunLiveUtil.java @@ -20,8 +20,8 @@ public class AliYunLiveUtil { /** * 根据源id创建该id的推流url * - * @param sourceId - * @param aliyunConfig + * @param sourceId 房间id + * @param aliyunConfig 阿里云配置 * @return */ public static String createPushUrl(String sourceId, AliYunLiveConfig aliyunConfig) { @@ -62,11 +62,11 @@ public class AliYunLiveUtil { /** * 创建拉流域名,key=rtmpUrl、flvUrl、m3u8Url,代表三种拉流类型域名 * - * @param sourceId - * @param aliyunConfig + * @param sourceId 房间id + * @param aliyunConfig 阿里云配置 * @return */ - public static String createPullUrl(String sourceId, AliYunLiveConfig aliyunConfig) { + public static String createPullUrl(String sourceId, AliYunLiveConfig aliyunConfig, Integer type) { // 拉流域名 String pullDomain = aliyunConfig.getPullDomain(); @@ -87,34 +87,43 @@ public class AliYunLiveUtil { String pullUrl = StrUtil.format("{}/{}/{}", pullDomain, appName, streamName); //log.info("组合通用域名,pullUrl=" + pullUrl); - // 组合md5加密串 - // /{appName}/{streamName}-{timestamp}-0-0-{pullIdentKey} - String md5Url = StrUtil.format("/{}/{}-{}-0-0-{}", appName, streamName, timestamp, pullIdentKey); - String md5FlvUrl = StrUtil.format("/{}/{}.flv-{}-0-0-{}", appName, streamName, timestamp, pullIdentKey); - String md5M3u8Url = StrUtil.format("/{}/{}.m3u8-{}-0-0-{}", appName, streamName, timestamp, pullIdentKey); - - // md5加密 - String md5Str = DigestUtil.md5Hex(md5Url); - String md5FlvStr = DigestUtil.md5Hex(md5FlvUrl); - String md5M3u8Str = DigestUtil.md5Hex(md5M3u8Url); - log.info("md5加密串,md5Url: {}, md5Str: {}", md5Url, md5Str); - log.info("md5加密串,md5FlvUrl: {}, md5FlvStr: {}", md5FlvUrl, md5FlvStr); - log.info("md5加密串,md5M3u8Url: {}, md5M3u8Str: {}", md5M3u8Url, md5M3u8Str); - + String url; // 组合三种拉流域名前缀 - // rtmp://{pullUrl}?auth_key={timestamp}-0-0-{md5Str} - String rtmpUrl = StrUtil.format("rtmp://{}?auth_key={}-0-0-{}", pullUrl, timestamp, md5Str); - // http://{pullUrl}.flv?auth_key={timestamp}-0-0-{md5FlvStr} - String flvUrl = StrUtil.format("http://{}.flv?auth_key={}-0-0-{}", pullUrl, timestamp, md5FlvStr); - // http://{pullUrl}.m3u8?auth_key={timestamp}-0-0-{md5M3u8Str} - String m3u8Url = StrUtil.format("http://{}.m3u8?auth_key={}-0-0-{}", pullUrl, timestamp, md5M3u8Str); - - log.info("最终鉴权过的拉流rtmp域名=" + rtmpUrl); - log.info("最终鉴权过的拉流flv域名 =" + flvUrl); - log.info("最终鉴权过的拉流m3u8域名=" + m3u8Url); - - // 微信小程序推流组件只支持 rtmp - return rtmpUrl; + switch (type) { + case 1: { + // 组合md5加密串 + // /{appName}/{streamName}-{timestamp}-0-0-{pullIdentKey} + String md5Url = StrUtil.format("/{}/{}-{}-0-0-{}", appName, streamName, timestamp, pullIdentKey); + // md5加密 + String md5Str = DigestUtil.md5Hex(md5Url); + log.info("md5加密串,md5Url: {}, md5Str: {}", md5Url, md5Str); + // rtmp://{pullUrl}?auth_key={timestamp}-0-0-{md5Str} + url = StrUtil.format("rtmp://{}?auth_key={}-0-0-{}", pullUrl, timestamp, md5Str); + log.info("最终鉴权过的拉流rtmp域名: {}", url); + break; + } + case 2: { + String md5FlvUrl = StrUtil.format("/{}/{}.flv-{}-0-0-{}", appName, streamName, timestamp, pullIdentKey); + String md5FlvStr = DigestUtil.md5Hex(md5FlvUrl); + log.info("md5加密串,md5FlvUrl: {}, md5FlvStr: {}", md5FlvUrl, md5FlvStr); + // http://{pullUrl}.flv?auth_key={timestamp}-0-0-{md5FlvStr} + url = StrUtil.format("http://{}.flv?auth_key={}-0-0-{}", pullUrl, timestamp, md5FlvStr); + log.info("最终鉴权过的拉流flv域名: {}", url); + break; + } + case 3: { + String md5M3u8Url = StrUtil.format("/{}/{}.m3u8-{}-0-0-{}", appName, streamName, timestamp, pullIdentKey); + String md5M3u8Str = DigestUtil.md5Hex(md5M3u8Url); + log.info("md5加密串,md5M3u8Url: {}, md5M3u8Str: {}", md5M3u8Url, md5M3u8Str); + // http://{pullUrl}.m3u8?auth_key={timestamp}-0-0-{md5M3u8Str} + url = StrUtil.format("http://{}.m3u8?auth_key={}-0-0-{}", pullUrl, timestamp, md5M3u8Str); + log.info("最终鉴权过的拉流m3u8域名: {}", url); + break; + } + default: + throw new IllegalStateException("Unexpected value: " + type); + } + return url; } } diff --git a/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java b/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java index 450c3fc..853a757 100644 --- a/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java +++ b/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java @@ -25,6 +25,7 @@ public class LiveEndopint { /** * 使用map来收集session,key为roomName,value为同一个房间的用户集合 * concurrentMap的key不存在时报错,不是返回null + * 房间id : 房间用户列表 */ private static final Map> ROOMS = new ConcurrentHashMap(); @@ -90,7 +91,7 @@ public class LiveEndopint { @OnClose public void disConnect(@PathParam("roomId") String roomId, Session session) { ROOMS.get(roomId).remove(session); - System.out.println("a client has disconnected!"); + log.info("用户{}退出直播间", name); } diff --git a/src/test/java/com/zgn/fazhi/Test2.java b/src/test/java/com/zgn/fazhi/Test2.java index eba5c4c..7a81f5b 100644 --- a/src/test/java/com/zgn/fazhi/Test2.java +++ b/src/test/java/com/zgn/fazhi/Test2.java @@ -4,10 +4,12 @@ import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.PutObjectRequest; import com.zgn.fazhi.mapper.ExaminationMapper; +import com.zgn.fazhi.mapper.LiveInfoMapper; import com.zgn.fazhi.pojo.po.Chapter; import com.zgn.fazhi.pojo.po.Examination; import com.zgn.fazhi.pojo.po.ExaminationtTypeOption; import com.zgn.fazhi.pojo.po.UserInfo; +import com.zgn.fazhi.pojo.vo.UserLiveInfo; import com.zgn.fazhi.service.ChapterService; import com.zgn.fazhi.service.ExaminationService; import com.zgn.fazhi.utils.RedisUtil; @@ -24,7 +26,7 @@ import java.util.*; import java.util.stream.Collectors; @Slf4j -@SpringBootTest +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class Test2 { @Autowired @@ -232,8 +234,12 @@ public class Test2 { } + @Autowired + private LiveInfoMapper liveInfoMapper; + @Test public void test16(){ - + List allLive = liveInfoMapper.getAllLive(); + allLive.forEach(System.out::println); } } -- Gitee From 0098efd4b0c5edb4a4672de3454f0999d1655ff5 Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Wed, 18 Aug 2021 10:01:28 +0800 Subject: [PATCH 03/13] =?UTF-8?q?=E6=9B=B4=E6=AD=A3controller=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3token=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zgn/fazhi/controller/AppointmentController.java | 8 ++++---- .../com/zgn/fazhi/controller/EvaluateController.java | 4 ++-- .../zgn/fazhi/controller/ExaminationController.java | 4 ++-- .../fazhi/controller/ExaminationRecordController.java | 10 +++++----- .../java/com/zgn/fazhi/controller/ExcelController.java | 6 +++--- .../java/com/zgn/fazhi/controller/FileController.java | 2 +- .../zgn/fazhi/controller/FileResourcesController.java | 4 ++-- .../fazhi/controller/GeneralExaminationController.java | 2 +- .../java/com/zgn/fazhi/controller/ImageController.java | 2 +- .../com/zgn/fazhi/controller/TeacherExaController.java | 8 ++++---- .../controller/UserExaminationScoreController.java | 2 +- .../com/zgn/fazhi/controller/UserInfoController.java | 4 ++-- .../com/zgn/fazhi/controller/UserTimeController.java | 4 ++-- .../java/com/zgn/fazhi/controller/VideoController.java | 2 +- .../java/com/zgn/fazhi/controller/WrongController.java | 6 +++--- .../zgn/fazhi/service/impl/AliYunLivServiceImpl.java | 9 ++++++--- 16 files changed, 40 insertions(+), 37 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/controller/AppointmentController.java b/src/main/java/com/zgn/fazhi/controller/AppointmentController.java index 5d0d19b..0ed061c 100644 --- a/src/main/java/com/zgn/fazhi/controller/AppointmentController.java +++ b/src/main/java/com/zgn/fazhi/controller/AppointmentController.java @@ -56,11 +56,11 @@ public class AppointmentController { // 获取全部可参观地点 return ResultFactory.buildSuccessResult(visitContentService.getAllVisitContent()); } - + @RequiresRoles(value = {"admin"}) @ApiOperation("通过id删除预约数据") @GetMapping("/api/delAppointment/{id}") - public Result delAppointment(@PathVariable Integer id, @RequestHeader("X-Authorization-With") String token) { + public Result delAppointment(@PathVariable Integer id, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { // 需要删除两张表的预约数据 appointmentService.delAppById(id); log.info("用户{}删除了一条预约记录", jwtUtils.getCurrentUserInfo(token)); @@ -70,7 +70,7 @@ public class AppointmentController { @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @ApiOperation("查询当前用户的预约情况") @GetMapping("/api/getCurrentAppointment") - public Result getCurrentAppointment(@RequestHeader("X-Authorization-With") String token) { + public Result getCurrentAppointment(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { // 查询用户的预约情况 return ResultFactory.buildSuccessResult(appointmentService.findAllByUid(JwtUtils.getUidByToken(token))); } @@ -85,7 +85,7 @@ public class AppointmentController { @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @ApiOperation("插入预约记录") @PostMapping("/api/insertAppointment") - public Result insertAppointment(@Valid @RequestBody AppointmentInfo info, @RequestHeader("X-Authorization-With") String token) { + public Result insertAppointment(@Valid @RequestBody AppointmentInfo info, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { // 获取当前用户,并设置当前用户id // 插入前 需要判断当日日期 时间段预约是否满人 Appointment appointment = info.getInfo(); diff --git a/src/main/java/com/zgn/fazhi/controller/EvaluateController.java b/src/main/java/com/zgn/fazhi/controller/EvaluateController.java index 4606ee4..f10dce6 100644 --- a/src/main/java/com/zgn/fazhi/controller/EvaluateController.java +++ b/src/main/java/com/zgn/fazhi/controller/EvaluateController.java @@ -33,7 +33,7 @@ public class EvaluateController { @ApiOperation("插入评价") @PostMapping("/api/addEvaluate") - public Result addEvaluate(@RequestHeader("X-Authorization-With") String token, @RequestBody Evaluate evaluate){ + public Result addEvaluate(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @RequestBody Evaluate evaluate){ // 通过用户id查询是否已经评价 // 如果评价返回400,如果未评价,插入数据库 evaluateService.addEvaluate(evaluate, JwtUtils.getUidByToken(token)); @@ -42,7 +42,7 @@ public class EvaluateController { @ApiOperation("查询当前用户是否评价") @GetMapping("/api/getEvaluate") - public Result getEvaluate(@RequestHeader("X-Authorization-With") String token){ + public Result getEvaluate(@RequestHeader(JwtUtils.AUTH_HEADER) String token){ evaluateService.getEvaluate(JwtUtils.getUidByToken(token)); return ResultFactory.buildSuccessResult("用户未评价"); } diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationController.java index fa12fbb..41298ed 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationController.java @@ -91,14 +91,14 @@ public class ExaminationController { @ApiOperation("当前用户通过统考/练习id获取该次考试的所有题目") @GetMapping("/admin/getExaminationByRid/{rid}") - public Result getExaminationByRid(@RequestHeader("X-Authorization-With") String token, @PathVariable Integer rid) { + public Result getExaminationByRid(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer rid) { return ResultFactory.buildSuccessResult(generalExaminationService.findAllExaminationByRid(rid, JwtUtils.getUidByToken(token))); } @ApiOperation("当前用户通过考试/练习id获取该次考试/练习成绩") @GetMapping("/admin/getScore/{rid}") - public Result getScore(@RequestHeader("X-Authorization-With") String token, @PathVariable Integer rid) { + public Result getScore(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer rid) { // 通过当前用户uid和统考id获取该次考试成绩 UserInfo currentUserInfo = jwtUtils.getCurrentUserInfo(token); return ResultFactory.buildSuccessResult(userExaminationService.getScoreByUid(currentUserInfo.getId(), rid)); diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java index f4f3206..02fc21f 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java @@ -30,7 +30,7 @@ public class ExaminationRecordController { @ApiOperation("当前用户查询所有考试") @GetMapping("/api/getExamination") - public Result getExamination(@RequestHeader("X-Authorization-With") String token) { + public Result getExamination(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { return ResultFactory.buildSuccessResult(examinationRecordService.getExaminationByUid(jwtUtils.getCurrentUserInfo(token), 0)); } @@ -43,26 +43,26 @@ public class ExaminationRecordController { @ApiOperation("当前用户查询所有练习") @GetMapping("/api/getExercise") - public Result getExercise(@RequestHeader("X-Authorization-With") String token) { + public Result getExercise(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { return ResultFactory.buildSuccessResult(examinationRecordService.getExaminationByUid(jwtUtils.getCurrentUserInfo(token), 1)); } @ApiOperation("当前用户提交考试/练习") @PostMapping("/api/submitExamination") - public Result submitExamination(@RequestHeader("X-Authorization-With") String token, @RequestBody SubmitExamination submitExamination) { + public Result submitExamination(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @RequestBody SubmitExamination submitExamination) { return ResultFactory.buildSuccessResult(examinationRecordService.submitExamination(submitExamination.setUid(JwtUtils.getUidByToken(token)))); } @ApiOperation("查询所有考试/练习") @PostMapping("/admin/getExaList/{ifPractice}") - public Result getExaList(@PathVariable Integer ifPractice, @RequestHeader("X-Authorization-With") String token) { + public Result getExaList(@PathVariable Integer ifPractice, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { return ResultFactory.buildSuccessResult(examinationRecordService.getAllExa(ifPractice, jwtUtils.getCurrentUserInfo(token))); } @ApiOperation("后台开始一次统考") @PostMapping("/admin/addExaminationRecord") - public Result addExaminationRecord(@Valid @RequestBody AddRecord record, @RequestHeader("X-Authorization-With") String token) { + public Result addExaminationRecord(@Valid @RequestBody AddRecord record, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { record.getExaminationRecord().setUid(JwtUtils.getUidByToken(token)); // 从前端接收该次统考的基本设置和题型设置 examinationRecordService.addExaminationRecord(record); diff --git a/src/main/java/com/zgn/fazhi/controller/ExcelController.java b/src/main/java/com/zgn/fazhi/controller/ExcelController.java index 5e5e700..e55fe4c 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExcelController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExcelController.java @@ -77,7 +77,7 @@ public class ExcelController { @ApiOperation("管理员上传考题excel") @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType = "_file", name = "上传文件", required = true)}) public Result practiceFile(@ApiParam(value = "上传练习题", required = true) @RequestPart("file") MultipartFile file, - @RequestHeader("X-Authorization-With") String token) throws IOException { + @RequestHeader(JwtUtils.AUTH_HEADER) String token) throws IOException { checkFile(file); Integer uid = JwtUtils.getUidByToken(token); // 校验 @@ -95,7 +95,7 @@ public class ExcelController { @PostMapping(value = "/api/uploadExamination", consumes = "multipart/*", headers = "content-type=multipart/form-data") @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType = "_file", name = "上传文件", required = true)}) public Result examinationFile(@ApiParam(value = "上传考题", required = true) @RequestPart("file") MultipartFile file, - @RequestHeader("X-Authorization-With") String token) throws IOException { + @RequestHeader(JwtUtils.AUTH_HEADER) String token) throws IOException { // 导入后需要刷新每个级别、题型练习题缓存 // 判断文件是否为空 checkFile(file); @@ -116,7 +116,7 @@ public class ExcelController { @PostMapping(value = "/api/uploadUser", consumes = "multipart/*", headers = "content-type=multipart/form-data") @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType = "_file", name = "上传用户", required = true)}) public void userFile(@ApiParam(value = "上传用户", required = true) @RequestPart("file") MultipartFile file, - @RequestHeader("X-Authorization-With") String token, HttpServletResponse response) throws IOException { + @RequestHeader(JwtUtils.AUTH_HEADER) String token, HttpServletResponse response) throws IOException { // 判断文件是否为空 checkFile(file); Integer uid = JwtUtils.getUidByToken(token); diff --git a/src/main/java/com/zgn/fazhi/controller/FileController.java b/src/main/java/com/zgn/fazhi/controller/FileController.java index b6871a4..873680f 100644 --- a/src/main/java/com/zgn/fazhi/controller/FileController.java +++ b/src/main/java/com/zgn/fazhi/controller/FileController.java @@ -70,7 +70,7 @@ public class FileController { @ApiOperation("当前用户获取当前可见的视频") @GetMapping("/api/getCurrentFile/{typeId}") - public Result getCurrentFile(@PathVariable Integer typeId, @RequestHeader("X-Authorization-With") String token){ + public Result getCurrentFile(@PathVariable Integer typeId, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ return ResultFactory.buildSuccessResult(resourcesService.getResources(3, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); } diff --git a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java index 2b611c2..6fbe062 100644 --- a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java +++ b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java @@ -30,7 +30,7 @@ public class FileResourcesController { @ApiOperation("通过资源分类id和该资源分类id获取当前用户可见的资源") @GetMapping("/api/getResources/{rid}/{typeId}") public Result getResources(@PathVariable Integer rid, @PathVariable Integer typeId, - @RequestHeader("X-Authorization-With") String token) { + @RequestHeader(JwtUtils.AUTH_HEADER) String token) { return ResultFactory.buildSuccessResult( resourcesService.getResources(rid, jwtUtils.getCurrentUserInfo(token).getGradeId(), @@ -39,7 +39,7 @@ public class FileResourcesController { @ApiOperation("保存用户观看时间") @PostMapping("/api/saveUseTime") - public Result saveUseTime(@RequestBody @Valid UserTime userTime, @RequestHeader("X-Authorization-With") String token){ + public Result saveUseTime(@RequestBody @Valid UserTime userTime, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ resourcesService.saveUseTime(userTime, JwtUtils.getUidByToken(token)); return ResultFactory.buildSuccessResult("上传成功"); } diff --git a/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java b/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java index 492dfb9..8a51478 100644 --- a/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java +++ b/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java @@ -30,7 +30,7 @@ public class GeneralExaminationController { @ApiOperation("后台通过统考id插入该次统考的考题") @PostMapping("/admin/addAutoExamination") - public Result addAutoExamination(@RequestBody AddExamination examination, @RequestHeader("X-Authorization-With") String token) { + public Result addAutoExamination(@RequestBody AddExamination examination, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { generalExaminationService.addAutoExamination(examination, JwtUtils.getUidByToken(token)); return ResultFactory.buildSuccessResult("添加成功"); } diff --git a/src/main/java/com/zgn/fazhi/controller/ImageController.java b/src/main/java/com/zgn/fazhi/controller/ImageController.java index 42762bc..98ee944 100644 --- a/src/main/java/com/zgn/fazhi/controller/ImageController.java +++ b/src/main/java/com/zgn/fazhi/controller/ImageController.java @@ -69,7 +69,7 @@ public class ImageController { @ApiOperation("当前用户获取当前可见的视频") @GetMapping("/api/getCurrentImg/{typeId}") - public Result getCurrentImg(@PathVariable Integer typeId, @RequestHeader("X-Authorization-With") String token){ + public Result getCurrentImg(@PathVariable Integer typeId, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ return ResultFactory.buildSuccessResult(resourcesService.getResources(2, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); } diff --git a/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java b/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java index 703db53..8f920da 100644 --- a/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java +++ b/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java @@ -25,7 +25,7 @@ public class TeacherExaController { @ApiOperation("查询当前教师的题库") @GetMapping("/api/getTeacherExa") - public Result getTeacherExa(@RequestHeader("X-Authorization-With") String token) { + public Result getTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { // 返回缺少选项数据 return ResultFactory.buildSuccessResult( examinationService.selectAllByTid(JwtUtils.getUidByToken(token))); @@ -33,21 +33,21 @@ public class TeacherExaController { @ApiOperation("教师删除考题") @GetMapping("/api/delTeacherExa/{eid}") - public Result delTeacherExa(@RequestHeader("X-Authorization-With") String token, @PathVariable Integer eid) { + public Result delTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer eid) { examinationService.delTeacherExaById(eid, JwtUtils.getUidByToken(token)); return ResultFactory.buildSuccessResult("删除成功"); } @ApiOperation("教师向私有题库添加单个考题") @PostMapping("/api/addTeacherExa") - public Result addTeacherExa(@RequestHeader("X-Authorization-With") String token, @RequestBody @Valid ExaminationOption examination) { + public Result addTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @RequestBody @Valid ExaminationOption examination) { examinationService.addExaminationTeacher(JwtUtils.getUidByToken(token), examination); return ResultFactory.buildSuccessResult("添加成功"); } @ApiOperation("教师修改考题") @PostMapping("/api/updateTeacherExa") - public Result updateTeacherExa(@RequestHeader("X-Authorization-With") String token, @Valid @RequestBody Examination examination) { + public Result updateTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @Valid @RequestBody Examination examination) { examinationService.updateById(examination.setTeacherId(JwtUtils.getUidByToken(token))); return ResultFactory.buildSuccessResult("修改成功"); } diff --git a/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java b/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java index 791e997..769878d 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java @@ -25,7 +25,7 @@ public class UserExaminationScoreController { @ApiOperation("查询当前用户对该次考试练习的成绩") @GetMapping("/api/getCurrentExaDate/{rid}") - public Result getCurrentExaDate(@RequestHeader("X-Authorization-With") String token, @PathVariable Integer rid) { + public Result getCurrentExaDate(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer rid) { return ResultFactory.buildSuccessResult( userExaminationScoreService.getCurrentExaDateByUid(jwtUtils.getCurrentUserInfo(token).getId(), rid)); diff --git a/src/main/java/com/zgn/fazhi/controller/UserInfoController.java b/src/main/java/com/zgn/fazhi/controller/UserInfoController.java index d6e78aa..c482ea7 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserInfoController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserInfoController.java @@ -81,7 +81,7 @@ public class UserInfoController { @ApiOperation("获取当前用户信息") @GetMapping("api/getCurrentUserInfo") - public Result getCurrentUserInfo(@RequestHeader("X-Authorization-With") String token) { + public Result getCurrentUserInfo(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { return ResultFactory.buildSuccessResult(userInfoService .selectByUsername(jwtUtils.getCurrentUserInfo(token) .getUsername())); @@ -89,7 +89,7 @@ public class UserInfoController { @ApiOperation("用户修改密码") @PostMapping("api/updatePassword") - public Result getCurrentUserInfo(@RequestBody UserInfo user, @RequestHeader("X-Authorization-With") String token) { + public Result getCurrentUserInfo(@RequestBody UserInfo user, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { // 通过jwt获取当前用户 // 修改当前用户密码 UserInfo userInfo = userInfoService.findByUsername(jwtUtils.getCurrentUserInfo(token).getUsername()); diff --git a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java index 8fdf8f6..d458e38 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java @@ -22,14 +22,14 @@ public class UserTimeController { @ApiOperation("获取当前用户等级") @GetMapping("/getRankByThisUser") - public Result getRankByThisUser(@RequestHeader("X-Authorization-With") String token){ + public Result getRankByThisUser(@RequestHeader(JwtUtils.AUTH_HEADER) String token){ UserInfo currentUserInfo = jwtUtils.getCurrentUserInfo(token); return ResultFactory.buildSuccessResult(userTimeService.getRankByTimeLength(currentUserInfo.getId())); } @ApiOperation("提交当前用户在线时长数据") @PostMapping("/api/saveUserTime") - public Result saveUserTime(@RequestBody Integer time, @RequestHeader("X-Authorization-With") String token){ + public Result saveUserTime(@RequestBody Integer time, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ userTimeService.saveUserTime(jwtUtils.getCurrentUserInfo(token).getId(), time); return ResultFactory.buildSuccessResult("保存成功"); } diff --git a/src/main/java/com/zgn/fazhi/controller/VideoController.java b/src/main/java/com/zgn/fazhi/controller/VideoController.java index 3b9be44..49e7fc1 100644 --- a/src/main/java/com/zgn/fazhi/controller/VideoController.java +++ b/src/main/java/com/zgn/fazhi/controller/VideoController.java @@ -67,7 +67,7 @@ public class VideoController { @ApiOperation("当前用户获取当前可见的视频") @GetMapping("/api/getCurrentVideo/{typeId}") - public Result getCurrentVideo(@PathVariable Integer typeId, @RequestHeader("X-Authorization-With") String token){ + public Result getCurrentVideo(@PathVariable Integer typeId, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ return ResultFactory.buildSuccessResult(resourcesService.getResources(1, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); } } diff --git a/src/main/java/com/zgn/fazhi/controller/WrongController.java b/src/main/java/com/zgn/fazhi/controller/WrongController.java index dcf00ae..ed8be4c 100644 --- a/src/main/java/com/zgn/fazhi/controller/WrongController.java +++ b/src/main/java/com/zgn/fazhi/controller/WrongController.java @@ -29,14 +29,14 @@ public class WrongController { @ApiOperation("查询当前用户的错题集") @GetMapping("api/getWrong") - public Result getWrong(@RequestHeader("X-Authorization-With") String token) { + public Result getWrong(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { List wrongs = wrongService.findByUid(jwtUtils.getCurrentUserInfo(token).getId()); return ResultFactory.buildSuccessResult(wrongs); } @ApiOperation("当前用户添加错题") @GetMapping("api/addWrong/{pid}") - public Result addWrong(@RequestHeader("X-Authorization-With") String token, @PathVariable Integer pid) { + public Result addWrong(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer pid) { // 获取当前用户id Integer uid = jwtUtils.getCurrentUserInfo(token).getId(); wrongService.addWrong(uid, pid); @@ -46,7 +46,7 @@ public class WrongController { @ApiOperation("当前用户删除错题") @GetMapping("api/delWrong/{pid}") - public Result delWrong(@RequestHeader("X-Authorization-With") String token, @PathVariable Integer pid) { + public Result delWrong(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer pid) { // 获取当前用户id Integer uid = jwtUtils.getCurrentUserInfo(token).getId(); wrongService.delWrong(uid, pid); diff --git a/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java index 3a20f77..528bc23 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java @@ -1,6 +1,5 @@ package com.zgn.fazhi.service.impl; -import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.zgn.fazhi.config.AliYunLiveConfig; import com.zgn.fazhi.exception.RestException; @@ -35,6 +34,11 @@ public class AliYunLivServiceImpl implements AliYunLiveService { */ private static final String CUTOFF = "publish_done"; + /** + * 拉流key刷新时间 29分钟 + */ + private static final long EXPIREDTIME = 60 * 29; + @Autowired private LiveInfoMapper liveInfoMapper; @@ -167,8 +171,7 @@ public class AliYunLivServiceImpl implements AliYunLiveService { } // 微信小程序直播只支持rtmp String pullUrl = AliYunLiveUtil.createPullUrl(lId.toString(), aliyunConfig, 3); - // 有效期设置29分钟 - redisUtil.setIfAbsent(key, pullUrl, 60 * 29); + redisUtil.setIfAbsent(key, pullUrl, EXPIREDTIME); // 生成播流地址 return pullUrl; } -- Gitee From 82054207cf0a83c814261703ae49975fd92bb91f Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Wed, 18 Aug 2021 14:30:53 +0800 Subject: [PATCH 04/13] =?UTF-8?q?=E8=B5=84=E6=BA=90=E9=93=BE=E6=8E=A5?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=8B=BC=E6=8E=A5=E5=89=8D=E7=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/zgn/fazhi/mapper/LiveInfoMapper.java | 2 +- .../java/com/zgn/fazhi/pojo/po/LiveInfo.java | 3 ++ .../com/zgn/fazhi/pojo/vo/UserLiveInfo.java | 3 ++ .../service/impl/AliYunLivServiceImpl.java | 32 +++++++++++----- .../service/impl/ResourcesServiceImpl.java | 37 ++++++++++++------- src/main/resources/application.properties | 2 +- src/test/java/com/zgn/fazhi/Test2.java | 8 +++- 7 files changed, 61 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java b/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java index fd1abca..8aacf83 100644 --- a/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java +++ b/src/main/java/com/zgn/fazhi/mapper/LiveInfoMapper.java @@ -23,7 +23,7 @@ public interface LiveInfoMapper extends BaseMapper { * * @return 所有直播间信息 */ - @Select("SELECT l.id, u.name, title, info, if_live " + + @Select("SELECT l.id, u.name, title, info, if_live, screenshot " + "FROM live_info AS l INNER JOIN user_info AS u ON l.uid = u.id") List getAllLive(); diff --git a/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java b/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java index a301040..f9963e7 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/LiveInfo.java @@ -45,4 +45,7 @@ public class LiveInfo implements Serializable { @ApiModelProperty("最后一次直播时间") private Date lastLive; + @ApiModelProperty("直播截图url") + private String screenshot; + } diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java b/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java index 4f395dd..acaee47 100644 --- a/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java +++ b/src/main/java/com/zgn/fazhi/pojo/vo/UserLiveInfo.java @@ -32,4 +32,7 @@ public class UserLiveInfo implements Serializable { @ApiModelProperty("是否正在直播") private Integer ifLive; + @ApiModelProperty("直播截图url") + private String screenshot; + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java index 528bc23..cee65be 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/AliYunLivServiceImpl.java @@ -2,6 +2,7 @@ package com.zgn.fazhi.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.zgn.fazhi.config.AliYunLiveConfig; +import com.zgn.fazhi.config.AliyunConfig; import com.zgn.fazhi.exception.RestException; import com.zgn.fazhi.mapper.LiveInfoMapper; import com.zgn.fazhi.pojo.po.LiveInfo; @@ -35,7 +36,7 @@ public class AliYunLivServiceImpl implements AliYunLiveService { private static final String CUTOFF = "publish_done"; /** - * 拉流key刷新时间 29分钟 + * 拉流key刷新时间 29分钟 */ private static final long EXPIREDTIME = 60 * 29; @@ -43,13 +44,16 @@ public class AliYunLivServiceImpl implements AliYunLiveService { private LiveInfoMapper liveInfoMapper; @Autowired - private AliYunLiveConfig aliyunConfig; + private AliYunLiveConfig aliyunLiveConfig; @Autowired private RedisUtil redisUtil; private static final String KEY = "onLiveKey"; + @Autowired + private AliyunConfig aliyunConfig; + @Override public void aliyunLiveCallback(ApiLiveModel model) { try { @@ -85,11 +89,11 @@ public class AliYunLivServiceImpl implements AliYunLiveService { public void saveLive(String sourceId) { try { //生成推流地址 - String pushUrl = AliYunLiveUtil.createPushUrl(sourceId, aliyunConfig); + String pushUrl = AliYunLiveUtil.createPushUrl(sourceId, aliyunLiveConfig); log.info("生成推流地址: {}", pushUrl); //生成播流地址 - String pullUrl = AliYunLiveUtil.createPullUrl(sourceId, aliyunConfig,3); + String pullUrl = AliYunLiveUtil.createPullUrl(sourceId, aliyunLiveConfig, 3); log.info("生成播流地址: {}", pullUrl); } catch (Exception e) { @@ -105,6 +109,9 @@ public class AliYunLivServiceImpl implements AliYunLiveService { // 如果为空,则为该用户新建直播间,并返回 liveInfo = new LiveInfo().setUid(uid); liveInfoMapper.insert(liveInfo); + // 生成房间号后添加直播截图地址 + liveInfo.setScreenshot("liveScreenshot/fazhi/" + liveInfo.getId() + ".jpg"); + liveInfoMapper.updateById(liveInfo); } return liveInfo; } @@ -117,7 +124,7 @@ public class AliYunLivServiceImpl implements AliYunLiveService { throw new RestException(400, "初始化直播间失败"); } // 根据房间id生成推流地址 - return AliYunLiveUtil.createPushUrl(roomId.toString(), aliyunConfig); + return AliYunLiveUtil.createPushUrl(roomId.toString(), aliyunLiveConfig); } @Override @@ -127,6 +134,7 @@ public class AliYunLivServiceImpl implements AliYunLiveService { liveInfo.setIfLive(null) .setUid(null) .setLastLive(null) + .setScreenshot(null) .setId(liveInfoMapper.selectOne( new QueryWrapper() .eq("uid", currentUserId)) @@ -155,7 +163,13 @@ public class AliYunLivServiceImpl implements AliYunLiveService { } private List getOnLive() { - return getAllLive().stream().filter(liveInfo -> liveInfo.getIfLive() == 1).collect(Collectors.toList()); + return getAllLive() + .stream() + // 筛选开播的 + .filter(liveInfo -> liveInfo.getIfLive() == 1) + // url添加前缀 + .peek(liveInfo -> liveInfo.setScreenshot(aliyunConfig.getUrlPrefix() + liveInfo.getScreenshot())) + .collect(Collectors.toList()); } @Override @@ -166,11 +180,11 @@ public class AliYunLivServiceImpl implements AliYunLiveService { if (redisUtil.hasKey(key)) { return redisUtil.get(key).toString(); } - } catch (RedisConnectionFailureException e){ - return AliYunLiveUtil.createPullUrl(lId.toString(), aliyunConfig, 3); + } catch (RedisConnectionFailureException e) { + return AliYunLiveUtil.createPullUrl(lId.toString(), aliyunLiveConfig, 3); } // 微信小程序直播只支持rtmp - String pullUrl = AliYunLiveUtil.createPullUrl(lId.toString(), aliyunConfig, 3); + String pullUrl = AliYunLiveUtil.createPullUrl(lId.toString(), aliyunLiveConfig, 3); redisUtil.setIfAbsent(key, pullUrl, EXPIREDTIME); // 生成播流地址 return pullUrl; diff --git a/src/main/java/com/zgn/fazhi/service/impl/ResourcesServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/ResourcesServiceImpl.java index b7523a3..a9f6753 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/ResourcesServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/ResourcesServiceImpl.java @@ -1,12 +1,10 @@ package com.zgn.fazhi.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.zgn.fazhi.config.AliyunConfig; import com.zgn.fazhi.exception.RestException; import com.zgn.fazhi.mapper.ResourcesMapper; -import com.zgn.fazhi.pojo.po.Resources; -import com.zgn.fazhi.pojo.po.UserFile; -import com.zgn.fazhi.pojo.po.UserGrade; -import com.zgn.fazhi.pojo.po.UserVideo; +import com.zgn.fazhi.pojo.po.*; import com.zgn.fazhi.pojo.vo.UserTime; import com.zgn.fazhi.service.*; import com.zgn.fazhi.utils.RedisUtil; @@ -19,6 +17,7 @@ import org.springframework.util.StringUtils; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; +import java.util.stream.Collectors; @Service @Slf4j @@ -46,30 +45,42 @@ public class ResourcesServiceImpl extends ServiceImpl resIdList; - if (StringUtils.isEmpty(gid)){ + if (StringUtils.isEmpty(gid)) { // 表示非学生 resIdList = permissionService.selectByTidAndEid(resTid, null, typeId); } else { // 通过学历id和资源分类id和详细分类id查询资源权限id集合 resIdList = permissionService.selectByTidAndEid(resTid, userGradeService.selectEidByGid(gid), typeId); } + String urlPrefix = aliyunConfig.getUrlPrefix(); switch (resTid) { case 1: { // 视频分类 - return videoService.listByIds(resIdList); + return videoService.listByIds(resIdList) + .stream() + .peek(video -> video + .setUrl(urlPrefix + video.getUrl()) + .setScreenshot(urlPrefix + video.getScreenshot())) + .collect(Collectors.toList()); } case 2: { // 图文分类 - return pictureService.listByIds(resIdList); + return pictureService.listByIds(resIdList) + .stream() + .peek(picture -> picture.setUrl(urlPrefix + picture.getUrl())) + .collect(Collectors.toList()); } case 3: { // 文档分类 - return fileService.listByIds(resIdList); + return fileService.listByIds(resIdList) + .stream() + .peek(file -> file.setUrl(urlPrefix + file.getUrl())) + .collect(Collectors.toList()); } default: { log.warn("当前分类不存在:{}", resTid); @@ -80,18 +91,18 @@ public class ResourcesServiceImpl extends ServiceImpl allLive = liveInfoMapper.getAllLive(); - allLive.forEach(System.out::println); + List allLiveIfOn = aliYunLiveService.getAllLiveIfOn(); + allLiveIfOn.forEach(System.out::println); } } -- Gitee From ab3e4cb8b34bfe35cb53208a3e501cf99ec697db Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Wed, 18 Aug 2021 20:13:03 +0800 Subject: [PATCH 05/13] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=9F=BA=E4=BA=8Enetty?= =?UTF-8?q?=E7=9A=84websocket=E8=81=8A=E5=A4=A9=E5=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 + .../com/zgn/fazhi/config/WebSocketConfig.java | 2 +- .../zgn/fazhi/ws/GetUserInfoConfigurator.java | 1 + .../java/com/zgn/fazhi/ws/LiveEndopint.java | 2 +- .../zgn/fazhi/ws/NettyWebsocketEndpoint.java | 187 ++++++++++++++++++ src/main/resources/application.properties | 6 +- 6 files changed, 200 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java diff --git a/pom.xml b/pom.xml index cd23c3a..5143dd3 100644 --- a/pom.xml +++ b/pom.xml @@ -48,6 +48,11 @@ javacv 1.4.3 + + org.yeauty + netty-websocket-spring-boot-starter + 0.11.0 + org.bytedeco.javacpp-presets diff --git a/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java b/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java index 2e498e5..3458994 100644 --- a/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java +++ b/src/main/java/com/zgn/fazhi/config/WebSocketConfig.java @@ -2,7 +2,7 @@ package com.zgn.fazhi.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.socket.server.standard.ServerEndpointExporter; +import org.yeauty.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { diff --git a/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java b/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java index c5c986d..4d7243a 100644 --- a/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java +++ b/src/main/java/com/zgn/fazhi/ws/GetUserInfoConfigurator.java @@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; +import java.util.List; import java.util.Map; @Slf4j diff --git a/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java b/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java index 853a757..99ff832 100644 --- a/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java +++ b/src/main/java/com/zgn/fazhi/ws/LiveEndopint.java @@ -16,9 +16,9 @@ import java.util.concurrent.ConcurrentHashMap; /** * 直播间即时通信 websoket + * 已停用,使用netty版本的websocket */ @Slf4j -@Component @ServerEndpoint(value = "/ws/live/{roomId}", configurator = GetUserInfoConfigurator.class) public class LiveEndopint { diff --git a/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java b/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java new file mode 100644 index 0000000..695cc89 --- /dev/null +++ b/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java @@ -0,0 +1,187 @@ +package com.zgn.fazhi.ws; + +import com.zgn.fazhi.pojo.po.UserInfo; +import com.zgn.fazhi.service.UserInfoService; +import com.zgn.fazhi.utils.JwtUtils; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.timeout.IdleStateEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.yeauty.annotation.*; +import org.yeauty.pojo.Session; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; + +/** + * @author ydw + * @version 1.0 + * @description 基于Netty的websoket服务端 + * @date 18/08/2021 2:56 PM + */ + +@Component +@Slf4j +@ServerEndpoint(path = "${ws.path}", port = "${ws.port}") +public class NettyWebsocketEndpoint { + + /** + * 使用map来收集session,key为roomName,value为同一个房间的用户集合 + * concurrentMap的key不存在时报错,不是返回null + * 房间id : 房间用户列表 + */ + private static final Map> ROOMS = new ConcurrentHashMap(); + + /** + * 当前用户session + */ + private Session session; + + private static UserInfoService userInfoService; + + @Autowired + public void setUserInfoService(UserInfoService userInfoService) { + NettyWebsocketEndpoint.userInfoService = userInfoService; + } + + private String currentName; + + /** + * 所在房间号 + */ + private String roomId; + + /** + * 客户端和服务端握手前 + * + * @param headers 请求头 + */ + @BeforeHandshake + public void handshake(HttpHeaders headers) { + try { + currentName = + userInfoService + .findByUid(JwtUtils.getUidByToken(headers.get(JwtUtils.AUTH_HEADER))) + .getName(); + } catch (NullPointerException e){ + currentName = "游客" + ThreadLocalRandom.current().nextInt(9999); + } + } + + /** + * 握手成功后,连接websocket + * + * @param session 用户session + */ + @OnOpen + public void onOpen(Session session, @PathVariable String roomId) throws Exception { + log.info("当前房间号 :{}", roomId); + // 保存session + this.session = session; + log.info("用户{}连接websocket", currentName); + this.roomId = roomId; + // 将session按照房间名来存储,将各个房间的用户隔离 + if (!ROOMS.containsKey(roomId)) { + // 创建房间不存在时,创建房间 + Set room = new HashSet<>(); + // 添加用户 + room.add(session); + ROOMS.put(roomId, room); + log.info("用户进入后: {}", ROOMS); + } else { + // 房间已存在,直接添加用户到相应的房间 + ROOMS.get(roomId).add(session); + } + String msg = "用户" + currentName + "进入房间" + roomId; + // 对该房间进行广播 + broadcast(roomId, msg); + log.info(msg); + } + + /** + * 客户端关闭ws事件 + * + * @param session 用户session + */ + @OnClose + public void onClose(Session session, @PathVariable String roomId) { + ROOMS.get(roomId).remove(session); + log.info("用户{}退出直播间", currentName); + } + + @OnError + public void onError(Session session, Throwable throwable) { + throwable.printStackTrace(); + } + + @OnMessage + public void onMessage(Session session, String msg) { + msg = currentName + ":" + msg; + log.info("向房间号:{}推送消息:{}", roomId, msg); + // 接收到信息后进行广播 + try { + broadcast(roomId, msg); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 当接收到二进制消息时,对该方法进行回调 + * + * @param session 用户session + * @param bytes 二进制消息 + */ + @OnBinary + public void onBinary(Session session, byte[] bytes) { + for (byte b : bytes) { + System.out.println(b); + } + session.sendBinary(bytes); + } + + + /** + * 当接收到Netty的事件时,对该方法进行回调 + * + * @param session 用户session + * @param evt 事件 + */ + @OnEvent + public void onEvent(Session session, Object evt) { + if (evt instanceof IdleStateEvent) { + IdleStateEvent idleStateEvent = (IdleStateEvent) evt; + switch (idleStateEvent.state()) { + case READER_IDLE: + System.out.println("read idle"); + break; + case WRITER_IDLE: + System.out.println("write idle"); + break; + case ALL_IDLE: + System.out.println("all idle"); + break; + default: + break; + } + } + } + + /** + * 按照房间id进行广播 + * + * @param roomId 房间id + * @param msg 消息 + * @throws Exception + */ + public static void broadcast(String roomId, String msg) throws Exception { + for (Session session : ROOMS.get(roomId)) { + session.sendText(msg); + } + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 252c46f..3c4d149 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -70,4 +70,8 @@ aliyunlive.region-id=cn-shenzhen # OSS-RAM 访问控制-人员管理-用户 AccessKey aliyunlive.access-key-id=LTAI5tEGVsxFYGxGY5VUAWuW # OSS-RAM 访问控制-人员管理-用户 secret -aliyunlive.secret=kgbtFAaenANkIGD4teY0LxKrrk89yK \ No newline at end of file +aliyunlive.secret=kgbtFAaenANkIGD4teY0LxKrrk89yK + +# nettyWebsocket 配置 +ws.path=/nettyWs/live/{roomId} +ws.port=8081 \ No newline at end of file -- Gitee From 5411e30be99e2c2767819297c9fc575aaecb7c30 Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Thu, 19 Aug 2021 12:54:34 +0800 Subject: [PATCH 06/13] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E5=9C=A8=E7=BA=BF=E6=97=B6=E9=95=BF=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fazhi/controller/UserTimeController.java | 9 +-- .../fazhi/controller/UserVideoController.java | 16 ++++- .../zgn/fazhi/controller/VideoController.java | 14 ++--- .../fazhi/controller/WebConfigController.java | 3 + .../zgn/fazhi/controller/WrongController.java | 21 ++++--- .../com/zgn/fazhi/mapper/UserTimeMapper.java | 13 +++- .../java/com/zgn/fazhi/pojo/po/UserTime.java | 3 - .../java/com/zgn/fazhi/pojo/po/UserVideo.java | 5 ++ .../com/zgn/fazhi/pojo/vo/UserTimeData.java | 11 +++- .../com/zgn/fazhi/pojo/vo/UserVideoDate.java | 6 ++ .../zgn/fazhi/service/UserVideoService.java | 7 +++ .../service/impl/RankInfoServiceImpl.java | 24 ++++++- .../service/impl/UserTimeServiceImpl.java | 63 +++++++++++-------- .../service/impl/UserVideoServiceImpl.java | 18 ++++++ .../zgn/fazhi/ws/NettyWebsocketEndpoint.java | 21 ++++--- 15 files changed, 163 insertions(+), 71 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java index d458e38..4a64aa3 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java @@ -14,26 +14,23 @@ import org.springframework.web.bind.annotation.*; @RestController public class UserTimeController { - @Autowired - private JwtUtils jwtUtils; - @Autowired private UserTimeService userTimeService; @ApiOperation("获取当前用户等级") @GetMapping("/getRankByThisUser") public Result getRankByThisUser(@RequestHeader(JwtUtils.AUTH_HEADER) String token){ - UserInfo currentUserInfo = jwtUtils.getCurrentUserInfo(token); - return ResultFactory.buildSuccessResult(userTimeService.getRankByTimeLength(currentUserInfo.getId())); + return ResultFactory.buildSuccessResult(userTimeService.getRankByTimeLength(JwtUtils.getUidByToken(token))); } @ApiOperation("提交当前用户在线时长数据") @PostMapping("/api/saveUserTime") public Result saveUserTime(@RequestBody Integer time, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ - userTimeService.saveUserTime(jwtUtils.getCurrentUserInfo(token).getId(), time); + userTimeService.saveUserTime(JwtUtils.getUidByToken(token), time); return ResultFactory.buildSuccessResult("保存成功"); } + @ApiOperation("获取所有用户的在线时长数据") @GetMapping("/admin/getUserTimeData") public Result getUserTimeData(){ return ResultFactory.buildSuccessResult(userTimeService.getUserTimeData()); diff --git a/src/main/java/com/zgn/fazhi/controller/UserVideoController.java b/src/main/java/com/zgn/fazhi/controller/UserVideoController.java index 349aa0b..a04d0e8 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserVideoController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserVideoController.java @@ -1,14 +1,17 @@ package com.zgn.fazhi.controller; import com.zgn.fazhi.factory.ResultFactory; +import com.zgn.fazhi.pojo.po.UserVideo; +import com.zgn.fazhi.pojo.po.Video; import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.UserVideoService; +import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; @Api(tags = "视频后台数据分析接口") @RestController @@ -29,4 +32,11 @@ public class UserVideoController { return ResultFactory.buildSuccessResult(userVideoService.getUserVideoInfoByUid(uid)); } + @ApiOperation("上传用户观看视频时长") + @PostMapping("/api/saveVideoTime") + public Result saveVideoTime(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @RequestBody @Valid UserVideo userVideo){ + userVideoService.saveVideoTime(userVideo.setUid(JwtUtils.getUidByToken(token))); + return ResultFactory.buildSuccessResult("保存成功"); + } + } diff --git a/src/main/java/com/zgn/fazhi/controller/VideoController.java b/src/main/java/com/zgn/fazhi/controller/VideoController.java index 49e7fc1..2c300ec 100644 --- a/src/main/java/com/zgn/fazhi/controller/VideoController.java +++ b/src/main/java/com/zgn/fazhi/controller/VideoController.java @@ -32,7 +32,7 @@ public class VideoController { @Autowired private JwtUtils jwtUtils; - + @ApiOperation("上传视频,需要前端生成随机的id,用于查询上传进度") @RequiresRoles(value = {"admin"}) @PostMapping(value = "/admin/videoUpload",consumes = "multipart/*",headers = "content-type=multipart/form-data") public Result videoUpload(@ModelAttribute @Valid FileUploadForm fileUploadForm) { @@ -40,6 +40,7 @@ public class VideoController { return ResultFactory.buildSuccessResult("上传成功"); } + @ApiOperation("根据id删除视频") @RequiresRoles(value = {"admin"}) @GetMapping("/admin/videoDelete/{id}") public Result videoDelete(@PathVariable Integer id) { @@ -47,17 +48,13 @@ public class VideoController { return ResultFactory.buildSuccessResult("删除成功"); } - /** - * 查看该分类所有文件 - */ + @ApiOperation("通过视频分类id获取该分类所有视频") @GetMapping("/admin/videoList/{id}") public Result videoList(@PathVariable Integer id) { return ResultFactory.buildSuccessResult(videoService.listByTid(id)); } - /** - * 修改文件信息 - */ + @ApiOperation("根据id更新视频信息") @RequiresRoles(value = {"admin"}) @PostMapping("/admin/videoUpdate") public Result videoUpdate(@RequestBody @Valid Video video){ @@ -68,6 +65,7 @@ public class VideoController { @ApiOperation("当前用户获取当前可见的视频") @GetMapping("/api/getCurrentVideo/{typeId}") public Result getCurrentVideo(@PathVariable Integer typeId, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ - return ResultFactory.buildSuccessResult(resourcesService.getResources(1, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); + return ResultFactory.buildSuccessResult( + resourcesService.getResources(1, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); } } diff --git a/src/main/java/com/zgn/fazhi/controller/WebConfigController.java b/src/main/java/com/zgn/fazhi/controller/WebConfigController.java index d6372e1..219c510 100644 --- a/src/main/java/com/zgn/fazhi/controller/WebConfigController.java +++ b/src/main/java/com/zgn/fazhi/controller/WebConfigController.java @@ -4,6 +4,7 @@ import com.zgn.fazhi.factory.ResultFactory; import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.WebConfigService; import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; @@ -19,6 +20,7 @@ public class WebConfigController { @Autowired private WebConfigService webConfigService; + @ApiOperation("更新用户注册时生成的用户名长度, 默认为6") @RequiresRoles(value = {"admin"}) @GetMapping("/admin/updateUsernameLength/{length}") public Result updateUsernameLength(@NotNull(message = "长度为空") @PathVariable Integer length){ @@ -26,6 +28,7 @@ public class WebConfigController { return ResultFactory.buildSuccessResult("修改成功"); } + @ApiOperation("获取当前注册时的用户名长度") @GetMapping("/admin/getUsernameLength") public Result getUsernameLength(){ return ResultFactory.buildSuccessResult(webConfigService.getUserNameLength()); diff --git a/src/main/java/com/zgn/fazhi/controller/WrongController.java b/src/main/java/com/zgn/fazhi/controller/WrongController.java index ed8be4c..335f248 100644 --- a/src/main/java/com/zgn/fazhi/controller/WrongController.java +++ b/src/main/java/com/zgn/fazhi/controller/WrongController.java @@ -7,6 +7,8 @@ import com.zgn.fazhi.service.WrongService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -24,22 +26,17 @@ public class WrongController { @Autowired private WrongService wrongService; - @Autowired - private JwtUtils jwtUtils; - @ApiOperation("查询当前用户的错题集") @GetMapping("api/getWrong") public Result getWrong(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { - List wrongs = wrongService.findByUid(jwtUtils.getCurrentUserInfo(token).getId()); - return ResultFactory.buildSuccessResult(wrongs); + return ResultFactory.buildSuccessResult(wrongService.findByUid(JwtUtils.getUidByToken(token))); } @ApiOperation("当前用户添加错题") @GetMapping("api/addWrong/{pid}") public Result addWrong(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer pid) { // 获取当前用户id - Integer uid = jwtUtils.getCurrentUserInfo(token).getId(); - wrongService.addWrong(uid, pid); + wrongService.addWrong(JwtUtils.getUidByToken(token), pid); return ResultFactory.buildSuccessResult("添加成功"); } @@ -48,9 +45,15 @@ public class WrongController { @GetMapping("api/delWrong/{pid}") public Result delWrong(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer pid) { // 获取当前用户id - Integer uid = jwtUtils.getCurrentUserInfo(token).getId(); - wrongService.delWrong(uid, pid); + wrongService.delWrong(JwtUtils.getUidByToken(token), pid); return ResultFactory.buildSuccessResult("删除成功"); } + @ApiOperation("查询某个用户的错题集") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) + @GetMapping("api/selectWrongByUid/{uid}") + public Result selectWrongByUid(@PathVariable Integer uid){ + return ResultFactory.buildSuccessResult(wrongService.findByUid(uid)); + } + } diff --git a/src/main/java/com/zgn/fazhi/mapper/UserTimeMapper.java b/src/main/java/com/zgn/fazhi/mapper/UserTimeMapper.java index f4c14e3..23f24d8 100644 --- a/src/main/java/com/zgn/fazhi/mapper/UserTimeMapper.java +++ b/src/main/java/com/zgn/fazhi/mapper/UserTimeMapper.java @@ -2,6 +2,7 @@ package com.zgn.fazhi.mapper; import com.zgn.fazhi.pojo.po.UserTime; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.zgn.fazhi.pojo.vo.UserTimeData; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @@ -24,9 +25,15 @@ public interface UserTimeMapper extends BaseMapper { @Select("select time_length from user_time where uid=#{uid}") Integer timeLength(@Param("uid") Integer id); - @Select("select time_length from rank_info") - ArrayList rankTime(); - @Select("select name from rank_info where time_length=#{timeL}") String getName(@Param("timeL") Integer timeL); + + /** + * 查询所有有使用时长数据的用户数据 + * @return + */ + @Select("SELECT uid, time_length, name " + + "FROM user_time AS time INNER JOIN user_info AS info ON time.uid = info.id") + List selectAllData(); + } diff --git a/src/main/java/com/zgn/fazhi/pojo/po/UserTime.java b/src/main/java/com/zgn/fazhi/pojo/po/UserTime.java index 9a3609a..bcaafcc 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/UserTime.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/UserTime.java @@ -36,8 +36,5 @@ public class UserTime implements Serializable { @ApiModelProperty(value = "使用时长") private Integer timeLength; - @ApiModelProperty(value = "等级id") - private Integer rankId; - } diff --git a/src/main/java/com/zgn/fazhi/pojo/po/UserVideo.java b/src/main/java/com/zgn/fazhi/pojo/po/UserVideo.java index 3d0be54..506b3cc 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/UserVideo.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/UserVideo.java @@ -13,6 +13,8 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; +import javax.validation.constraints.NotNull; + /** *

* @@ -36,15 +38,18 @@ public class UserVideo implements Serializable { @ApiModelProperty(value = "用户id") private Integer uid; + @NotNull(message = "视频id不能为空") @ApiModelProperty(value = "视频id") private Integer vid; + @NotNull(message = "播放起点为空") @ApiModelProperty(value = "开始播放时间点") private Date start; @ApiModelProperty(value = "播放时长单位s") private Integer length; + @NotNull(message = "播放结束点为空") @ApiModelProperty(value = "结束播放时间点") private Date end; diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/UserTimeData.java b/src/main/java/com/zgn/fazhi/pojo/vo/UserTimeData.java index 3a023b4..e39b814 100644 --- a/src/main/java/com/zgn/fazhi/pojo/vo/UserTimeData.java +++ b/src/main/java/com/zgn/fazhi/pojo/vo/UserTimeData.java @@ -11,10 +11,19 @@ public class UserTimeData implements Serializable { private static final long serialVersionUID = 1L; + /** + * 用户id + */ private Integer uid; + /** + * 用户名 + */ private String name; - private Integer time; + /** + * 使用时长 + */ + private Integer timeLength; } diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/UserVideoDate.java b/src/main/java/com/zgn/fazhi/pojo/vo/UserVideoDate.java index a658d8c..8e4cbac 100644 --- a/src/main/java/com/zgn/fazhi/pojo/vo/UserVideoDate.java +++ b/src/main/java/com/zgn/fazhi/pojo/vo/UserVideoDate.java @@ -13,8 +13,14 @@ public class UserVideoDate implements Serializable { private static final long serialVersionUID = 1L; + /** + * 所有观看视频记录 + */ private List userVideo; + /** + * 播放总时长 + */ private Integer totalTime; } diff --git a/src/main/java/com/zgn/fazhi/service/UserVideoService.java b/src/main/java/com/zgn/fazhi/service/UserVideoService.java index 60b15c8..41a5fb5 100644 --- a/src/main/java/com/zgn/fazhi/service/UserVideoService.java +++ b/src/main/java/com/zgn/fazhi/service/UserVideoService.java @@ -25,4 +25,11 @@ public interface UserVideoService extends IService { UserVideoDate getUserVideoInfoByUid(Integer uid); + /** + * 保存用户观看视频时间 + * @param userVideo + * @return + */ + Boolean saveVideoTime(UserVideo userVideo); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/RankInfoServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/RankInfoServiceImpl.java index 468f9d0..3ffc783 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/RankInfoServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/RankInfoServiceImpl.java @@ -4,7 +4,11 @@ import com.zgn.fazhi.pojo.po.RankInfo; import com.zgn.fazhi.mapper.RankInfoMapper; import com.zgn.fazhi.service.RankInfoService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.zgn.fazhi.utils.FastJsonUtils; +import com.zgn.fazhi.utils.RedisUtil; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.stereotype.Service; import java.util.List; @@ -18,31 +22,49 @@ import java.util.List; * @since 2021-06-25 */ @Service +@Slf4j public class RankInfoServiceImpl extends ServiceImpl implements RankInfoService { @Autowired private RankInfoMapper rankInfoMapper; + @Autowired + private RedisUtil redisUtil; + + private static final String KEY = "rankInfoKey"; + @Override public List getRank() { - return rankInfoMapper.selectList(null); + try { + if (redisUtil.hasKey(KEY)){ + return FastJsonUtils.toList(redisUtil.get(KEY), RankInfo.class); + } + } catch (RedisConnectionFailureException e){ + return rankInfoMapper.selectList(null); + } + List rankInfos = rankInfoMapper.selectList(null); + redisUtil.setIfAbsent(KEY, rankInfos, RedisUtil.EXPIRETIME); + return rankInfos; } @Override public Boolean updateRank(RankInfo rankInfo) { rankInfoMapper.updateById(rankInfo); + redisUtil.del(KEY); return true; } @Override public Boolean deleteRank(Integer id) { rankInfoMapper.deleteById(id); + redisUtil.del(KEY); return true; } @Override public Boolean addRank(RankInfo rankInfo) { rankInfoMapper.insert(rankInfo); + redisUtil.del(KEY); return true; } } diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java index b82efd6..3826982 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java @@ -6,6 +6,7 @@ import com.zgn.fazhi.pojo.po.RankInfo; import com.zgn.fazhi.pojo.po.UserTime; import com.zgn.fazhi.mapper.UserTimeMapper; import com.zgn.fazhi.pojo.vo.UserTimeData; +import com.zgn.fazhi.service.RankInfoService; import com.zgn.fazhi.service.UserInfoService; import com.zgn.fazhi.service.UserTimeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @@ -14,11 +15,13 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; +import java.util.OptionalInt; /** *

- * 服务实现类 + * 服务实现类 *

* * @author wt @@ -26,52 +29,58 @@ import java.util.List; */ @Service public class UserTimeServiceImpl extends ServiceImpl implements UserTimeService { + @Autowired private UserTimeMapper userTimeMapper; @Autowired private UserInfoService userInfoService; + @Autowired + private RankInfoService rankInfoService; + @Override - public String getRankByTimeLength(Integer id) { - Integer userTime = userTimeMapper.timeLength(id); - ArrayList rankTime = userTimeMapper.rankTime(); - Integer ranks = null; - for (Integer date : rankTime) { - if (userTime > date){ - ranks = date; - } + public String getRankByTimeLength(Integer uid) { + // 所有等级所需的时间 + List rankList = rankInfoService.getRank(); + + // 查询用户使用时长 + Integer userTime = userTimeMapper.timeLength(uid); + if (StringUtils.isEmpty(userTime)) { + // 当前用户使用时长数据为空则返回最低等级 + return rankList.stream() + .min(Comparator.comparing(RankInfo::getTimeLength)) + .get() + .getName(); } - return userTimeMapper.getName(ranks); + return rankList.stream() + .filter(time -> time.getTimeLength() <= userTime) + .max(Comparator.comparing(RankInfo::getTimeLength)) + .get() + .getName(); } @Override public Boolean saveUserTime(Integer uid, Integer time) { + // 用户现在使用时长 UserTime userTime1 = userTimeMapper.selectOne(new QueryWrapper().eq("uid", uid)); if (StringUtils.isEmpty(userTime1)) { - UserTime userTime = new UserTime(); - userTime.setUid(uid) - .setTimeLength(time); - userTimeMapper.insert(userTime); + // 如果为空则插入 + userTimeMapper.insert( + new UserTime() + .setUid(uid) + .setTimeLength(time)); } else { - userTime1.setTimeLength(userTime1.getTimeLength() + time); - userTimeMapper.updateById(userTime1); + // 如果有则更新 + userTimeMapper.updateById( + userTime1.setTimeLength( + userTime1.getTimeLength() + time)); } return true; } @Override public List getUserTimeData() { - UserTimeData userTimeData = new UserTimeData(); - List userTimeDataList = new ArrayList<>(); - List userTimes = userTimeMapper.selectList(null); - userTimes.forEach(userTime -> { - Integer uid = userTime.getUid(); - userTimeData.setUid(uid) - .setTime(userTime.getTimeLength()) - .setName(userInfoService.getById(uid).getName()); - userTimeDataList.add(userTimeData); - }); - return userTimeDataList; + return userTimeMapper.selectAllData(); } } diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserVideoServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserVideoServiceImpl.java index 03d363e..faab5d1 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserVideoServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserVideoServiceImpl.java @@ -1,6 +1,7 @@ package com.zgn.fazhi.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.zgn.fazhi.exception.RestException; import com.zgn.fazhi.pojo.po.UserInfo; import com.zgn.fazhi.pojo.po.UserVideo; import com.zgn.fazhi.mapper.UserVideoMapper; @@ -11,8 +12,11 @@ import com.zgn.fazhi.service.UserVideoService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import javax.validation.constraints.NotNull; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -72,4 +76,18 @@ public class UserVideoServiceImpl extends ServiceImpl= end){ + throw new RestException(400, "开始时间不能大于结束时间"); + } + if (StringUtils.isEmpty(userVideo.getLength())){ + userVideo.setLength((int)(end - start)/10); + } + userVideoMapper.insert(userVideo); + return true; + } } diff --git a/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java b/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java index 695cc89..a97c5ad 100644 --- a/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java +++ b/src/main/java/com/zgn/fazhi/ws/NettyWebsocketEndpoint.java @@ -1,6 +1,5 @@ package com.zgn.fazhi.ws; -import com.zgn.fazhi.pojo.po.UserInfo; import com.zgn.fazhi.service.UserInfoService; import com.zgn.fazhi.utils.JwtUtils; import io.netty.handler.codec.http.HttpHeaders; @@ -55,6 +54,8 @@ public class NettyWebsocketEndpoint { */ private String roomId; + private static final String HEART_BEAT = "ping"; + /** * 客户端和服务端握手前 * @@ -67,7 +68,7 @@ public class NettyWebsocketEndpoint { userInfoService .findByUid(JwtUtils.getUidByToken(headers.get(JwtUtils.AUTH_HEADER))) .getName(); - } catch (NullPointerException e){ + } catch (NullPointerException e) { currentName = "游客" + ThreadLocalRandom.current().nextInt(9999); } } @@ -120,13 +121,14 @@ public class NettyWebsocketEndpoint { @OnMessage public void onMessage(Session session, String msg) { - msg = currentName + ":" + msg; - log.info("向房间号:{}推送消息:{}", roomId, msg); - // 接收到信息后进行广播 - try { + // 判断是否为心跳 + if (HEART_BEAT.equals(msg)) { + session.sendText("pong"); + } else { + msg = currentName + ":" + msg; + log.info("向房间号:{}推送消息:{}", roomId, msg); + // 接收到信息后进行广播 broadcast(roomId, msg); - } catch (Exception e) { - e.printStackTrace(); } } @@ -176,9 +178,8 @@ public class NettyWebsocketEndpoint { * * @param roomId 房间id * @param msg 消息 - * @throws Exception */ - public static void broadcast(String roomId, String msg) throws Exception { + public static void broadcast(String roomId, String msg) { for (Session session : ROOMS.get(roomId)) { session.sendText(msg); } -- Gitee From 8aa70ee006fa5249a3d17ebd15ffafe603f805f4 Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Thu, 19 Aug 2021 17:11:00 +0800 Subject: [PATCH 07/13] =?UTF-8?q?=E5=AE=8C=E6=88=90oss=E5=88=86=E7=89=87?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FileResourcesController.java | 11 +++ .../fazhi/controller/UserTimeController.java | 1 - .../listener/PutObjectProgressListener.java | 14 ++- .../zgn/fazhi/pojo/dto/FileUploadIndex.java | 31 ++++++ .../zgn/fazhi/service/FileUploadService.java | 7 ++ .../service/impl/FileUploadServiceImpl.java | 97 ++++++++++++++++++- .../service/impl/UserTimeServiceImpl.java | 3 - 7 files changed, 147 insertions(+), 17 deletions(-) create mode 100644 src/main/java/com/zgn/fazhi/pojo/dto/FileUploadIndex.java diff --git a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java index 6fbe062..ad99595 100644 --- a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java +++ b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java @@ -3,6 +3,7 @@ package com.zgn.fazhi.controller; import com.zgn.fazhi.factory.ResultFactory; import com.zgn.fazhi.pojo.vo.UserTime; import com.zgn.fazhi.result.Result; +import com.zgn.fazhi.service.FileUploadService; import com.zgn.fazhi.service.ResourcesService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; @@ -19,6 +20,9 @@ public class FileResourcesController { @Autowired private ResourcesService resourcesService; + @Autowired + private FileUploadService fileUploadService; + @Autowired private JwtUtils jwtUtils; @@ -44,4 +48,11 @@ public class FileResourcesController { return ResultFactory.buildSuccessResult("上传成功"); } + @ApiOperation("取消上传") + @GetMapping("/admin/cancelUpload/{uploadId}") + public Result cancelUpload(@PathVariable Integer uploadId){ + fileUploadService.cancelUpload(uploadId); + return ResultFactory.buildSuccessResult("取消成功"); + } + } diff --git a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java index 4a64aa3..28c6422 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java @@ -1,7 +1,6 @@ package com.zgn.fazhi.controller; import com.zgn.fazhi.factory.ResultFactory; -import com.zgn.fazhi.pojo.po.UserInfo; import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.UserTimeService; import com.zgn.fazhi.utils.JwtUtils; diff --git a/src/main/java/com/zgn/fazhi/listener/PutObjectProgressListener.java b/src/main/java/com/zgn/fazhi/listener/PutObjectProgressListener.java index 2291cca..ca4f41b 100644 --- a/src/main/java/com/zgn/fazhi/listener/PutObjectProgressListener.java +++ b/src/main/java/com/zgn/fazhi/listener/PutObjectProgressListener.java @@ -17,22 +17,23 @@ public class PutObjectProgressListener implements ProgressListener { private RedisUtil redisUtil; - private static final String UPLOADKEY = "uploadPercent:"; + private long bytesWritten = 0; private long totalBytes = -1; private boolean succeed = false; + private long size; private String uploadId; - public PutObjectProgressListener(Integer id, RedisUtil redisUtil) { + public PutObjectProgressListener(Integer id, RedisUtil redisUtil, long size) { this.redisUtil = redisUtil; - this.uploadId = UPLOADKEY + id; - redisUtil.set(UPLOADKEY + id, 0); + this.size = size; } @Override public void progressChanged(ProgressEvent progressEvent) { long bytes = progressEvent.getBytes(); + log.debug("文件总共大小: {}", bytes); ProgressEventType eventType = progressEvent.getEventType(); switch (eventType) { case TRANSFER_STARTED_EVENT: @@ -47,22 +48,19 @@ public class PutObjectProgressListener implements ProgressListener { if (this.totalBytes != -1) { int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes); log.debug(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")"); - redisUtil.set(uploadId, percent); } else { + log.debug("进度: {}%", (int) (this.bytesWritten * 100.0 / size)); log.debug(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)"); } break; case TRANSFER_COMPLETED_EVENT: this.succeed = true; log.debug("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total"); - redisUtil.del(uploadId); break; case TRANSFER_FAILED_EVENT: log.debug("Failed to upload, " + this.bytesWritten + " bytes have been transferred"); - redisUtil.del(uploadId); break; default: - redisUtil.del(uploadId); break; } } diff --git a/src/main/java/com/zgn/fazhi/pojo/dto/FileUploadIndex.java b/src/main/java/com/zgn/fazhi/pojo/dto/FileUploadIndex.java new file mode 100644 index 0000000..5080ede --- /dev/null +++ b/src/main/java/com/zgn/fazhi/pojo/dto/FileUploadIndex.java @@ -0,0 +1,31 @@ +package com.zgn.fazhi.pojo.dto; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author ydw + * @version 1.0 + * @description TODO + * @date 19/08/2021 3:55 PM + */ + +@Data +@Accessors(chain = true) +public class FileUploadIndex implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 上传id + */ + private String uploadId; + + /** + * 上传路径 + */ + private String uploadPath; + +} diff --git a/src/main/java/com/zgn/fazhi/service/FileUploadService.java b/src/main/java/com/zgn/fazhi/service/FileUploadService.java index 0a24dd8..24fc594 100644 --- a/src/main/java/com/zgn/fazhi/service/FileUploadService.java +++ b/src/main/java/com/zgn/fazhi/service/FileUploadService.java @@ -28,4 +28,11 @@ public interface FileUploadService { Boolean upload(InputStream input, String filepath); + /** + * 取消上传 + * @param uploadId 上传id + * @reture + */ + Boolean cancelUpload(Integer uploadId); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java index b4f4600..db6adb0 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java @@ -1,11 +1,13 @@ package com.zgn.fazhi.service.impl; import com.aliyun.oss.OSS; -import com.aliyun.oss.model.PutObjectRequest; +import com.aliyun.oss.model.*; import com.zgn.fazhi.config.AliyunConfig; import com.zgn.fazhi.exception.RestException; import com.zgn.fazhi.listener.PutObjectProgressListener; +import com.zgn.fazhi.pojo.dto.FileUploadIndex; import com.zgn.fazhi.service.FileUploadService; +import com.zgn.fazhi.utils.FastJsonUtils; import com.zgn.fazhi.utils.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -14,6 +16,8 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.*; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; @@ -30,6 +34,15 @@ public class FileUploadServiceImpl implements FileUploadService { @Autowired private RedisUtil redisUtil; + private static final String UPLOAD_KEY = "uploadPercent:"; + + /** + * 每个分片的大小,用于计算文件有多少个分片。单位为字节 ,当前设置为1mb 1 * 1024 * 1024L + */ + private static final long PART_SIZE = 1024 * 1024L; + + private static final String CANCEL_KEY = "CANCEL_UPLOAD_KEY:"; + @Override public String upload(MultipartFile uploadFile, String fileType, Integer detailedTypeId, String pattern, Integer id) { @@ -39,13 +52,12 @@ public class FileUploadServiceImpl implements FileUploadService { String filePath = getFilePath(fileName, fileType, detailedTypeId); log.info("上传文件的OSS路径为: " + filePath); - // 上传阿里云OSS + long size = uploadFile.getSize(); + // 分片上传 try { - ossClient.putObject(new PutObjectRequest(aliyunConfig.getBucketName(), filePath, - new ByteArrayInputStream(uploadFile.getBytes())).withProgressListener(new PutObjectProgressListener(id, redisUtil))); + fragmentation(uploadFile, id.toString(), filePath); } catch (Exception e) { e.printStackTrace(); - //上传失败 throw new RestException(400, "上传失败"); } return filePath; @@ -103,4 +115,79 @@ public class FileUploadServiceImpl implements FileUploadService { return fileName; } + private void fragmentation(MultipartFile uploadFile, String uploadId1, String filePath) throws IOException { + String bucketName = aliyunConfig.getBucketName(); + // 创建InitiateMultipartUploadRequest对象 + InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, filePath); + // 初始化分片。 + InitiateMultipartUploadResult upResult = ossClient.initiateMultipartUpload(request); + // 蛇者uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。 + String uploadId = upResult.getUploadId(); + // 保存生成id至redis中 + redisUtil.set(CANCEL_KEY + uploadId1, + new FileUploadIndex() + .setUploadId(uploadId) + .setUploadPath(filePath), 60 * 30); + // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成 + List partETags = new ArrayList<>(); + + // 计算文件大小 + long fileLength = uploadFile.getSize(); + int partCount = (int) (fileLength / PART_SIZE); + log.info("上传片数: {}", partCount); + if (fileLength % PART_SIZE != 0) { + partCount++; + } + String key = UPLOAD_KEY + uploadId1; + // 遍历分片上传。 + for (int i = 0; i < partCount; i++) { + log.info("========= 上传第{}个分片", i + 1); + // 设置当前进度 + int i1 = i * 100 / partCount; + log.info("当前进度: {}", i1); + redisUtil.set(key, i1 + "%", 60 * 5); + + long startPos = i * PART_SIZE; + long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : PART_SIZE; + InputStream inputStream = new ByteArrayInputStream(uploadFile.getBytes()); + // 跳过已经上传的分片。 + inputStream.skip(startPos); + UploadPartRequest uploadPartRequest = new UploadPartRequest(); + uploadPartRequest.setBucketName(bucketName); + uploadPartRequest.setKey(filePath); + uploadPartRequest.setUploadId(uploadId); + uploadPartRequest.setInputStream(inputStream); + // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。 + uploadPartRequest.setPartSize(curPartSize); + // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。 + uploadPartRequest.setPartNumber(i + 1); + // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 + UploadPartResult uploadPartResult = ossClient.uploadPart( + uploadPartRequest.withProgressListener(new PutObjectProgressListener(Integer.parseInt(uploadId1), redisUtil, fileLength))); + + // 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。 + partETags.add(uploadPartResult.getPartETag()); + } + log.info("上传进度: 100%"); + redisUtil.set(key, "100%", 60 * 5); + + // 创建CompleteMultipartUploadRequest对象。 + // 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后, + // 会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 + // 完成上传。 + ossClient.completeMultipartUpload(new CompleteMultipartUploadRequest(bucketName, filePath, uploadId, partETags)); + } + + @Override + public Boolean cancelUpload(Integer uploadId) { + String key = CANCEL_KEY + uploadId; + FileUploadIndex fileUploadIndex = FastJsonUtils.toBean(redisUtil.get(key), FileUploadIndex.class); + // 取消分片上传。 + ossClient.abortMultipartUpload( + new AbortMultipartUploadRequest(aliyunConfig.getBucketName(), + fileUploadIndex.getUploadPath(), + fileUploadIndex.getUploadId())); + redisUtil.del(key); + return true; + } } diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java index 3826982..8c24f53 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserTimeServiceImpl.java @@ -33,9 +33,6 @@ public class UserTimeServiceImpl extends ServiceImpl i @Autowired private UserTimeMapper userTimeMapper; - @Autowired - private UserInfoService userInfoService; - @Autowired private RankInfoService rankInfoService; -- Gitee From 6bcaade6d430d13f52e165706a494a97f900cec3 Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Thu, 19 Aug 2021 17:24:02 +0800 Subject: [PATCH 08/13] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E8=BF=9B=E5=BA=A6=E6=9D=A1=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fazhi/controller/FileResourcesController.java | 8 ++++++++ .../com/zgn/fazhi/service/FileUploadService.java | 7 +++++++ .../fazhi/service/impl/FileUploadServiceImpl.java | 15 ++++++++++++--- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java index ad99595..0a4ee9a 100644 --- a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java +++ b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java @@ -55,4 +55,12 @@ public class FileResourcesController { return ResultFactory.buildSuccessResult("取消成功"); } + @ApiOperation("查看上传进度") + @GetMapping("/admin/getProgress/{uploadId}") + public Result getProgress(@PathVariable Integer uploadId){ + return ResultFactory.buildSuccessResult(fileUploadService.getProgress(uploadId)); + } + + + } diff --git a/src/main/java/com/zgn/fazhi/service/FileUploadService.java b/src/main/java/com/zgn/fazhi/service/FileUploadService.java index 24fc594..781c8b5 100644 --- a/src/main/java/com/zgn/fazhi/service/FileUploadService.java +++ b/src/main/java/com/zgn/fazhi/service/FileUploadService.java @@ -35,4 +35,11 @@ public interface FileUploadService { */ Boolean cancelUpload(Integer uploadId); + /** + * 查看上传进度 + * @param uploadId 上传id + * @return + */ + Integer getProgress(Integer uploadId); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java index db6adb0..274fa9f 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/FileUploadServiceImpl.java @@ -144,8 +144,8 @@ public class FileUploadServiceImpl implements FileUploadService { log.info("========= 上传第{}个分片", i + 1); // 设置当前进度 int i1 = i * 100 / partCount; - log.info("当前进度: {}", i1); - redisUtil.set(key, i1 + "%", 60 * 5); + log.info("当前进度: {}", i1 + "%"); + redisUtil.set(key, i1, 60 * 5); long startPos = i * PART_SIZE; long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : PART_SIZE; @@ -169,7 +169,7 @@ public class FileUploadServiceImpl implements FileUploadService { partETags.add(uploadPartResult.getPartETag()); } log.info("上传进度: 100%"); - redisUtil.set(key, "100%", 60 * 5); + redisUtil.set(key, 100, 60 * 5); // 创建CompleteMultipartUploadRequest对象。 // 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后, @@ -190,4 +190,13 @@ public class FileUploadServiceImpl implements FileUploadService { redisUtil.del(key); return true; } + + @Override + public Integer getProgress(Integer uploadId) { + try { + return Integer.parseInt(redisUtil.get(UPLOAD_KEY + uploadId).toString()); + } catch (NullPointerException e){ + throw new RestException(400, "该上传id无效"); + } + } } -- Gitee From b25d7fa941a63004f8bc8620b243dcece2ab7ab3 Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Fri, 20 Aug 2021 10:27:07 +0800 Subject: [PATCH 09/13] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fazhi/controller/ClassInfoController.java | 5 ++++ .../fazhi/controller/EducationController.java | 5 ++++ .../controller/EtypeScoreController.java | 6 +++++ .../ExaminationAnswerController.java | 6 +++++ .../controller/ExaminationController.java | 6 ++++- .../ExaminationPermissionController.java | 3 +++ .../ExaminationRecordController.java | 8 +++++-- .../zgn/fazhi/controller/ExcelController.java | 5 ++++ .../zgn/fazhi/controller/FileController.java | 24 ++++++++----------- .../controller/FileResourcesController.java | 3 +++ .../GeneralExaminationController.java | 3 +++ .../zgn/fazhi/controller/ImageController.java | 23 ++++++++---------- .../controller/IntervalInfoController.java | 5 ++++ .../controller/PermissionController.java | 5 ++++ .../zgn/fazhi/controller/RankController.java | 5 ++++ .../fazhi/controller/ResourcesController.java | 5 ++++ .../controller/TeacherExaController.java | 5 ++++ .../controller/UserExaminationController.java | 3 ++- .../fazhi/controller/UserFileController.java | 4 +++- .../fazhi/controller/UserGradeController.java | 5 ++++ .../fazhi/controller/UserTimeController.java | 3 +++ .../fazhi/controller/UserVideoController.java | 3 +++ 22 files changed, 108 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/controller/ClassInfoController.java b/src/main/java/com/zgn/fazhi/controller/ClassInfoController.java index 1d2554e..79e87a7 100644 --- a/src/main/java/com/zgn/fazhi/controller/ClassInfoController.java +++ b/src/main/java/com/zgn/fazhi/controller/ClassInfoController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.ClassInfoService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -30,6 +32,7 @@ public class ClassInfoController { } @ApiOperation("通过id删除班级") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/getClassInfo/{id}") public Result delClassInfoById(@PathVariable Integer id) { classInfoService.delClassInfo(id); @@ -37,6 +40,7 @@ public class ClassInfoController { } @ApiOperation("通过id修改班级") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/updateClassInfo") public Result updateClassInfo(@Valid @RequestBody ClassInfo classInfo) { classInfoService.updateClassInfoById(classInfo); @@ -44,6 +48,7 @@ public class ClassInfoController { } @ApiOperation("添加班级") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addClassInfo") public Result addClassInfoById(@Valid @RequestBody ClassInfo classInfo) { classInfoService.addClassInfo(classInfo); diff --git a/src/main/java/com/zgn/fazhi/controller/EducationController.java b/src/main/java/com/zgn/fazhi/controller/EducationController.java index f0d67e1..ad3b5a2 100644 --- a/src/main/java/com/zgn/fazhi/controller/EducationController.java +++ b/src/main/java/com/zgn/fazhi/controller/EducationController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.EducationService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -30,6 +32,7 @@ public class EducationController { } @ApiOperation("通过id删除学历") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/getEducation/{id}") public Result delEducationById(@PathVariable Integer id) { educationService.delEducation(id); @@ -37,6 +40,7 @@ public class EducationController { } @ApiOperation("通过id修改学历") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/updateEducation") public Result updateEducation(@Valid @RequestBody Education education) { educationService.updateEducationById(education); @@ -44,6 +48,7 @@ public class EducationController { } @ApiOperation("添加学历") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/addEducation") public Result addEducationById(@Valid @RequestBody Education education) { educationService.addEducation(education); diff --git a/src/main/java/com/zgn/fazhi/controller/EtypeScoreController.java b/src/main/java/com/zgn/fazhi/controller/EtypeScoreController.java index b64e0cd..0cd2fb2 100644 --- a/src/main/java/com/zgn/fazhi/controller/EtypeScoreController.java +++ b/src/main/java/com/zgn/fazhi/controller/EtypeScoreController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.EtypeScoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -20,6 +22,7 @@ public class EtypeScoreController { private EtypeScoreService etypeScoreService; @ApiOperation("修改配置") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/updateEtypeScore") public Result updateEtypeScore(@Valid @RequestBody EtypeScore etypeScore) { etypeScoreService.updateById(etypeScore); @@ -33,6 +36,7 @@ public class EtypeScoreController { } @ApiOperation("增加题目题型分数配置") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addEtypeScore") public Result addEtypeScore(@RequestBody @Valid List etypeScores){ etypeScoreService.saveBatch(etypeScores); @@ -40,6 +44,7 @@ public class EtypeScoreController { } @ApiOperation("通过id删除") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/delEtypeScoreById/{id}") public Result delEtypeScoreById(@PathVariable Integer id){ etypeScoreService.removeById(id); @@ -47,6 +52,7 @@ public class EtypeScoreController { } @ApiOperation("通过考试记录id删除所有配置") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/delEtypeScoreByRId/{id}") public Result delEtypeScoreByRId(@PathVariable Integer rid){ etypeScoreService.delByEid(rid); diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationAnswerController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationAnswerController.java index 5f49eff..289d0cb 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationAnswerController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationAnswerController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.ExaminationAnswerService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -20,6 +22,7 @@ public class ExaminationAnswerController { private ExaminationAnswerService examinationAnswerService; @ApiOperation("通过题目id删除该题目的所有选项") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/delOptionByEid/{eid}") public Result delOptionByEid(@PathVariable Integer eid){ examinationAnswerService.delAnswerListByEid(eid); @@ -27,12 +30,14 @@ public class ExaminationAnswerController { } @ApiOperation("通过题目id获取该题目的所有选项") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/api/getOptionByEid/{eid}") public Result getOptionByEid(@PathVariable Integer eid){ return ResultFactory.buildSuccessResult(examinationAnswerService.selectByEid(eid)); } @ApiOperation("通过id删除选项") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/delOptionById") public Result delOptionById(@RequestBody List idList){ examinationAnswerService.removeByIds(idList); @@ -40,6 +45,7 @@ public class ExaminationAnswerController { } @ApiOperation("通过id更新选项") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/updateOptionById") public Result updateOptionById(@RequestBody @Valid ExaminationAnswer examinationAnswer){ examinationAnswerService.updateById(examinationAnswer); diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationController.java index 41298ed..305084a 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationController.java @@ -12,6 +12,7 @@ import com.zgn.fazhi.service.UserExaminationService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -60,6 +61,7 @@ public class ExaminationController { } @ApiOperation("根据Id批量删除考题/练习题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/api/delBatchExa") public Result delBatchExa(@RequestBody List idList) { examinationService.removeByIds(idList); @@ -69,13 +71,14 @@ public class ExaminationController { } @ApiOperation("增加考题/练习题") - @RequiresRoles(value = {"admin"}) + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/api/addExa") public Result add(@RequestBody Examination examination) { return examinationService.addPaper(examination); } @ApiOperation("删除考题/练习题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/api/delExamination/{eid}") public Result delExamination(@PathVariable Integer eid) { // 通过考题id删除考题 @@ -84,6 +87,7 @@ public class ExaminationController { } @ApiOperation("根据Id修改考题/练习题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/api/updateExa") public Result updateId(@RequestBody Examination examination) { return examinationService.updatePaperById(examination); diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java index 672d12d..87a78af 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.ExaminationPermissionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -22,6 +24,7 @@ public class ExaminationPermissionController { private ExaminationPermissionService permissionService; @ApiOperation("通过id对考试或练习添加开放人群") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addExaPermission") public Result addExaPermission(@Valid @RequestBody ExaPermission exaPermission) { permissionService.addExaPermission(exaPermission); diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java index 02fc21f..4892ef2 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationRecordController.java @@ -9,6 +9,8 @@ import com.zgn.fazhi.service.ExaminationRecordService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -34,7 +36,8 @@ public class ExaminationRecordController { return ResultFactory.buildSuccessResult(examinationRecordService.getExaminationByUid(jwtUtils.getCurrentUserInfo(token), 0)); } - @ApiOperation("删除开始练习记录") + @ApiOperation("删除考试练习记录") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/delRecord") public Result delRecord(@PathVariable Integer rid){ examinationRecordService.delRecord(rid); @@ -60,7 +63,8 @@ public class ExaminationRecordController { } - @ApiOperation("后台开始一次统考") + @ApiOperation("后台开始一次考试练习") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addExaminationRecord") public Result addExaminationRecord(@Valid @RequestBody AddRecord record, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { record.getExaminationRecord().setUid(JwtUtils.getUidByToken(token)); diff --git a/src/main/java/com/zgn/fazhi/controller/ExcelController.java b/src/main/java/com/zgn/fazhi/controller/ExcelController.java index e55fe4c..7e90111 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExcelController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExcelController.java @@ -12,6 +12,8 @@ import com.zgn.fazhi.utils.JwtUtils; import com.zgn.fazhi.utils.RedisUtil; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -74,6 +76,7 @@ public class ExcelController { private UserGradeService userGradeService; @PostMapping(value = "/api/uploadPractice", consumes = "multipart/*", headers = "content-type=multipart/form-data") + @RequiresRoles(value = {"admin"}) @ApiOperation("管理员上传考题excel") @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType = "_file", name = "上传文件", required = true)}) public Result practiceFile(@ApiParam(value = "上传练习题", required = true) @RequestPart("file") MultipartFile file, @@ -91,6 +94,7 @@ public class ExcelController { return ResultFactory.buildSuccessResult("数据无误,导入成功"); } + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @ApiOperation("教师上传题库excel") @PostMapping(value = "/api/uploadExamination", consumes = "multipart/*", headers = "content-type=multipart/form-data") @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType = "_file", name = "上传文件", required = true)}) @@ -112,6 +116,7 @@ public class ExcelController { } + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @ApiOperation("上传用户excel") @PostMapping(value = "/api/uploadUser", consumes = "multipart/*", headers = "content-type=multipart/form-data") @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType = "_file", name = "上传用户", required = true)}) diff --git a/src/main/java/com/zgn/fazhi/controller/FileController.java b/src/main/java/com/zgn/fazhi/controller/FileController.java index 873680f..3e69b7e 100644 --- a/src/main/java/com/zgn/fazhi/controller/FileController.java +++ b/src/main/java/com/zgn/fazhi/controller/FileController.java @@ -10,6 +10,8 @@ import com.zgn.fazhi.service.ResourcesService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -32,36 +34,29 @@ public class FileController { @Autowired private JwtUtils jwtUtils; - /** - * 上传oss - * @param fileUploadForm 上传表单数据 - */ + @ApiOperation("上传文件") @PostMapping(value = "/admin/fileUpload",consumes = "multipart/*",headers = "content-type=multipart/form-data") public Result fileUpload(@ModelAttribute @Valid FileUploadForm fileUploadForm) { fileService.fileUpload(fileUploadForm); return ResultFactory.buildSuccessResult("上传成功"); } - /** - * 通过id删除文件 - */ + + @ApiOperation("通过id删除文件") @GetMapping("/admin/fileDelete/{id}") public Result delete(@PathVariable Integer id) { fileService.delById(id); return ResultFactory.buildSuccessResult("删除成功"); } - /** - * 查看该分类所有文件 - */ + @ApiOperation("查看该分类所有文件") @GetMapping("/admin/fileList/{id}") public Result fileList(@PathVariable Integer id) { return ResultFactory.buildSuccessResult(fileService.listByTid(id)); } - /** - * 修改文件信息 - */ + @ApiOperation("修改文件信息") + @RequiresRoles(value = {"admin"}) @PostMapping("/admin/fileUpdate") public Result fileUpdate(@RequestBody @Valid File file){ fileService.updateById(file); @@ -71,7 +66,8 @@ public class FileController { @ApiOperation("当前用户获取当前可见的视频") @GetMapping("/api/getCurrentFile/{typeId}") public Result getCurrentFile(@PathVariable Integer typeId, @RequestHeader(JwtUtils.AUTH_HEADER) String token){ - return ResultFactory.buildSuccessResult(resourcesService.getResources(3, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); + return ResultFactory.buildSuccessResult( + resourcesService.getResources(3, jwtUtils.getCurrentUserInfo(token).getGradeId(), typeId)); } diff --git a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java index 0a4ee9a..3bd789b 100644 --- a/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java +++ b/src/main/java/com/zgn/fazhi/controller/FileResourcesController.java @@ -8,6 +8,8 @@ import com.zgn.fazhi.service.ResourcesService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -49,6 +51,7 @@ public class FileResourcesController { } @ApiOperation("取消上传") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/cancelUpload/{uploadId}") public Result cancelUpload(@PathVariable Integer uploadId){ fileUploadService.cancelUpload(uploadId); diff --git a/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java b/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java index 8a51478..5610a23 100644 --- a/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java +++ b/src/main/java/com/zgn/fazhi/controller/GeneralExaminationController.java @@ -8,6 +8,8 @@ import com.zgn.fazhi.service.GeneralExaminationService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -29,6 +31,7 @@ public class GeneralExaminationController { private GeneralExaminationService generalExaminationService; @ApiOperation("后台通过统考id插入该次统考的考题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addAutoExamination") public Result addAutoExamination(@RequestBody AddExamination examination, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { generalExaminationService.addAutoExamination(examination, JwtUtils.getUidByToken(token)); diff --git a/src/main/java/com/zgn/fazhi/controller/ImageController.java b/src/main/java/com/zgn/fazhi/controller/ImageController.java index 98ee944..6ac4ded 100644 --- a/src/main/java/com/zgn/fazhi/controller/ImageController.java +++ b/src/main/java/com/zgn/fazhi/controller/ImageController.java @@ -10,6 +10,8 @@ import com.zgn.fazhi.service.ResourcesService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -31,36 +33,31 @@ public class ImageController { @Autowired private JwtUtils jwtUtils; - /** - * 上传oss - * @param fileUploadForm 上传表单数据 - */ + + @ApiOperation("上传表单数据") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping(value = "/admin/imgUpload",consumes = "multipart/*",headers = "content-type=multipart/form-data") public Result pictureUpload(@ModelAttribute @Valid FileUploadForm fileUploadForm) { pictureService.pictureUpload(fileUploadForm); return ResultFactory.buildSuccessResult("上传成功"); } - /** - * 通过id删除图片 - */ + @ApiOperation("通过id删除图片") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/imgDelete/{id}") public Result delete(@PathVariable Integer id) { pictureService.delById(id); return ResultFactory.buildSuccessResult("删除成功"); } - /** - * 查看该分类所有文件 - */ + @ApiOperation("查看该分类所有文件") @GetMapping("/admin/imgList/{id}") public Result imgList(@PathVariable Integer id) { return ResultFactory.buildSuccessResult(pictureService.listByTid(id)); } - /** - * 修改文件信息 - */ + @ApiOperation("修改文件信息") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/imgUpdate") public Result imgUpdate(@RequestBody @Valid Picture picture){ pictureService.updateById(picture); diff --git a/src/main/java/com/zgn/fazhi/controller/IntervalInfoController.java b/src/main/java/com/zgn/fazhi/controller/IntervalInfoController.java index 7678dca..c6f58aa 100644 --- a/src/main/java/com/zgn/fazhi/controller/IntervalInfoController.java +++ b/src/main/java/com/zgn/fazhi/controller/IntervalInfoController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.IntervalInfoService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -34,6 +36,7 @@ public class IntervalInfoController { } @ApiOperation("增加参观时间段") + @RequiresRoles(value = {"admin"}) @PostMapping("/api/addIntervalInfo") public Result addVisit(@RequestBody IntervalInfo intervalInfo){ intervalInfoService.addIntervalInfo(intervalInfo); @@ -41,6 +44,7 @@ public class IntervalInfoController { } @ApiOperation("删除参观时间段") + @RequiresRoles(value = {"admin"}) @GetMapping("/api/deleteIntervalInfo/{id}") public Result deleteVisit(@PathVariable Integer id){ intervalInfoService.deleteIntervalInfoById(id); @@ -48,6 +52,7 @@ public class IntervalInfoController { } @ApiOperation("修改参观时间段") + @RequiresRoles(value = {"admin"}) @PostMapping("/api/updateIntervalInfo") public Result updateVisit(@RequestBody IntervalInfo intervalInfo){ intervalInfoService.updateIntervalInfo(intervalInfo); diff --git a/src/main/java/com/zgn/fazhi/controller/PermissionController.java b/src/main/java/com/zgn/fazhi/controller/PermissionController.java index 02946ac..6322e36 100644 --- a/src/main/java/com/zgn/fazhi/controller/PermissionController.java +++ b/src/main/java/com/zgn/fazhi/controller/PermissionController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.PermissionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -22,6 +24,7 @@ public class PermissionController { private PermissionService permissionService; @ApiOperation("给某个资源添加权限") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addPermission") public Result addPermission(@RequestBody @Valid PermissionList permissionList){ permissionService.addPermission(permissionList); @@ -29,6 +32,7 @@ public class PermissionController { } @ApiOperation("给某个资源更新权限") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/updatePermission") public Result updatePermission(@RequestBody @Valid PermissionList permissionList){ permissionService.updatePermission(permissionList); @@ -36,6 +40,7 @@ public class PermissionController { } @ApiOperation("给某个资源的权限范围,资源分类id 和 该资源id") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/getPermissionList/{resTid}/{resId}") public Result getPermissionList(@PathVariable Integer resTid, @PathVariable Integer resId){ return ResultFactory.buildSuccessResult(permissionService.getByTidAndRid(resTid, resId)); diff --git a/src/main/java/com/zgn/fazhi/controller/RankController.java b/src/main/java/com/zgn/fazhi/controller/RankController.java index 1a7989e..accac11 100644 --- a/src/main/java/com/zgn/fazhi/controller/RankController.java +++ b/src/main/java/com/zgn/fazhi/controller/RankController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.RankInfoService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -28,6 +30,7 @@ public class RankController { } @ApiOperation("通过id删除等级") + @RequiresRoles(value = {"admin"}) @GetMapping("/delRank/{id}") public Result delRankById(@PathVariable Integer id) { rankInfoService.deleteRank(id); @@ -35,6 +38,7 @@ public class RankController { } @ApiOperation("通过id修改等级") + @RequiresRoles(value = {"admin"}) @PostMapping("/updateRank") public Result updateRank(@Valid @RequestBody RankInfo rankInfo) { rankInfoService.updateRank(rankInfo); @@ -42,6 +46,7 @@ public class RankController { } @ApiOperation("添加等级") + @RequiresRoles(value = {"admin"}) @PostMapping("/addRank") public Result addRankById(@Valid @RequestBody RankInfo rankInfo) { rankInfoService.addRank(rankInfo); diff --git a/src/main/java/com/zgn/fazhi/controller/ResourcesController.java b/src/main/java/com/zgn/fazhi/controller/ResourcesController.java index 3587e59..b3e453c 100644 --- a/src/main/java/com/zgn/fazhi/controller/ResourcesController.java +++ b/src/main/java/com/zgn/fazhi/controller/ResourcesController.java @@ -5,6 +5,8 @@ import com.zgn.fazhi.pojo.po.Resources; import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.ResourcesService; import io.swagger.annotations.Api; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -22,18 +24,21 @@ public class ResourcesController { return ResultFactory.buildSuccessResult(resourcesService.list()); } + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/delResources/{id}") public Result delResources(@PathVariable Integer id){ resourcesService.removeById(id); return ResultFactory.buildSuccessResult("删除成功"); } + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/addResources") public Result addResources(@RequestBody @Valid Resources resources){ resourcesService.save(resources); return ResultFactory.buildSuccessResult("添加成功"); } + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/admin/updateResources") public Result updateResources(@RequestBody Resources resources){ resourcesService.updateById(resources); diff --git a/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java b/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java index 8f920da..29fdeb9 100644 --- a/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java +++ b/src/main/java/com/zgn/fazhi/controller/TeacherExaController.java @@ -8,6 +8,8 @@ import com.zgn.fazhi.service.ExaminationService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -32,6 +34,7 @@ public class TeacherExaController { } @ApiOperation("教师删除考题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/api/delTeacherExa/{eid}") public Result delTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer eid) { examinationService.delTeacherExaById(eid, JwtUtils.getUidByToken(token)); @@ -39,6 +42,7 @@ public class TeacherExaController { } @ApiOperation("教师向私有题库添加单个考题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/api/addTeacherExa") public Result addTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @RequestBody @Valid ExaminationOption examination) { examinationService.addExaminationTeacher(JwtUtils.getUidByToken(token), examination); @@ -46,6 +50,7 @@ public class TeacherExaController { } @ApiOperation("教师修改考题") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/api/updateTeacherExa") public Result updateTeacherExa(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @Valid @RequestBody Examination examination) { examinationService.updateById(examination.setTeacherId(JwtUtils.getUidByToken(token))); diff --git a/src/main/java/com/zgn/fazhi/controller/UserExaminationController.java b/src/main/java/com/zgn/fazhi/controller/UserExaminationController.java index d2bd14d..dac8c95 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserExaminationController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserExaminationController.java @@ -6,6 +6,7 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.UserExaminationService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -24,7 +25,7 @@ public class UserExaminationController { private UserExaminationService userExaminationService; @ApiOperation("通过考试/练习id获取该次练习考试的数据") - @RequiresRoles(value = {"admin"}) + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/getExaData/{rid}") public Result getExaData(@PathVariable Integer rid) { return ResultFactory.buildSuccessResult(userExaminationService.getExaDataByRid(rid)); diff --git a/src/main/java/com/zgn/fazhi/controller/UserFileController.java b/src/main/java/com/zgn/fazhi/controller/UserFileController.java index 29ead79..5cccb44 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserFileController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserFileController.java @@ -4,6 +4,7 @@ import com.zgn.fazhi.factory.ResultFactory; import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.UserFileService; import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; @@ -18,13 +19,14 @@ public class UserFileController { @Autowired private UserFileService userFileService; + @ApiOperation("查询所有用户的浏览文件时长") @RequiresRoles(value = {"admin"}) @GetMapping("/admin/getFileTimeData") public Result getFileTimeData(){ return ResultFactory.buildSuccessResult(userFileService.getFileTimeData()); } - @RequiresRoles(value = {"admin"}) + @ApiOperation("获取用户浏览时长") @GetMapping("/api/getFileTimeDataByUid/{uid}") public Result getFileTimeDataByUid(@PathVariable Integer uid){ return ResultFactory.buildSuccessResult(userFileService.getById(uid).getLength()); diff --git a/src/main/java/com/zgn/fazhi/controller/UserGradeController.java b/src/main/java/com/zgn/fazhi/controller/UserGradeController.java index f88aec6..2197d72 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserGradeController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserGradeController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.UserGradeService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -30,6 +32,7 @@ public class UserGradeController { } @ApiOperation("通过id删除年级") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/getUserGrade/{id}") public Result delUserGradeById(@PathVariable Integer id) { userGradeService.delUserGrade(id); @@ -37,6 +40,7 @@ public class UserGradeController { } @ApiOperation("通过id修改年级") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/updateUserGrade") public Result updateUserGrade(@Valid @RequestBody UserGrade userGrade) { userGradeService.updateUserGradeById(userGrade); @@ -44,6 +48,7 @@ public class UserGradeController { } @ApiOperation("添加年级") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @PostMapping("/addUserGrade") public Result addUserGradeById(@Valid @RequestBody UserGrade userGrade) { userGradeService.addUserGrade(userGrade); diff --git a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java index 28c6422..1539437 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserTimeController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserTimeController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.service.UserTimeService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -30,6 +32,7 @@ public class UserTimeController { } @ApiOperation("获取所有用户的在线时长数据") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/getUserTimeData") public Result getUserTimeData(){ return ResultFactory.buildSuccessResult(userTimeService.getUserTimeData()); diff --git a/src/main/java/com/zgn/fazhi/controller/UserVideoController.java b/src/main/java/com/zgn/fazhi/controller/UserVideoController.java index a04d0e8..0e35247 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserVideoController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserVideoController.java @@ -8,6 +8,8 @@ import com.zgn.fazhi.service.UserVideoService; import com.zgn.fazhi.utils.JwtUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -21,6 +23,7 @@ public class UserVideoController { private UserVideoService userVideoService; @ApiOperation("获取所有用户的观看视频总时长") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) @GetMapping("/admin/getUserVideoData") public Result getUserVideoInfo(){ return ResultFactory.buildSuccessResult(userVideoService.getUserVideoInfo()); -- Gitee From b4ac09090fe7f4557ca150a9eacf73c696ffb4cd Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Fri, 20 Aug 2021 11:59:22 +0800 Subject: [PATCH 10/13] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=86=E4=BF=9D?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/SecretGuardController.java | 55 +++++++++++++++++++ .../fazhi/controller/UserInfoController.java | 49 +++++++++++------ .../zgn/fazhi/mapper/SecretGuardMapper.java | 16 ++++++ .../com/zgn/fazhi/mapper/UserInfoMapper.java | 22 ++++++++ .../com/zgn/fazhi/pojo/po/SecretGuard.java | 7 +++ .../zgn/fazhi/service/SecretGuardService.java | 14 +++++ .../zgn/fazhi/service/UserInfoService.java | 23 ++++++++ .../service/impl/SecretGuardServiceImpl.java | 21 +++++++ .../service/impl/UserInfoServiceImpl.java | 42 ++++++++++++-- .../impl/SecretGuardServiceImplTest.java | 26 +++++++++ 10 files changed, 252 insertions(+), 23 deletions(-) create mode 100644 src/main/java/com/zgn/fazhi/controller/SecretGuardController.java create mode 100644 src/main/java/com/zgn/fazhi/mapper/SecretGuardMapper.java create mode 100644 src/main/java/com/zgn/fazhi/service/SecretGuardService.java create mode 100644 src/main/java/com/zgn/fazhi/service/impl/SecretGuardServiceImpl.java create mode 100644 src/test/java/com/zgn/fazhi/service/impl/SecretGuardServiceImplTest.java diff --git a/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java b/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java new file mode 100644 index 0000000..460792d --- /dev/null +++ b/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java @@ -0,0 +1,55 @@ +package com.zgn.fazhi.controller; + +import com.zgn.fazhi.factory.ResultFactory; +import com.zgn.fazhi.pojo.po.SecretGuard; +import com.zgn.fazhi.result.Result; +import com.zgn.fazhi.service.SecretGuardService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + * @author ydw + * @version 1.0 + * @description 密保 + * @date 20/08/2021 11:43 AM + */ + +@Api(tags = "密保管理") +@RestController +public class SecretGuardController { + + @Autowired + private SecretGuardService secretGuardService; + + @ApiOperation("查询所有密保问题") + @GetMapping("/api/getSecretGuard") + public Result getSecretGuard() { + return ResultFactory.buildSuccessResult(secretGuardService.list()); + } + + @ApiOperation("增加密保问题") + @PostMapping("/api/saveSecretGuard") + public Result addSecretGuard(@RequestBody SecretGuard secretGuard) { + secretGuardService.save(secretGuard); + return ResultFactory.buildSuccessResult("添加成功"); + } + + @ApiOperation("根据id删除密保问题") + @PostMapping("/api/delSecretGuard") + public Result delSecretGuard(@RequestParam("id") Integer id){ + secretGuardService.removeById(id); + return ResultFactory.buildSuccessResult("删除成功"); + } + + @ApiOperation("根据id更新密保问题") + @PostMapping("/api/updateSecretGuard") + public Result updateSecretGuard(@RequestBody @Valid SecretGuard secretGuard){ + secretGuardService.updateById(secretGuard); + return ResultFactory.buildSuccessResult("更新成功"); + } + +} diff --git a/src/main/java/com/zgn/fazhi/controller/UserInfoController.java b/src/main/java/com/zgn/fazhi/controller/UserInfoController.java index c482ea7..c7df7e5 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserInfoController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserInfoController.java @@ -14,6 +14,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; @@ -29,14 +30,14 @@ public class UserInfoController { @ApiOperation("根据用户身份查找") @RequiresRoles(value = {"admin"}) - @GetMapping("api/userInfo/{rid}") + @GetMapping("/api/userInfo/{rid}") public Result selectUser(@PathVariable Integer rid) { return ResultFactory.buildSuccessResult(userInfoService.selectRoleId(rid)); } @ApiOperation("用户注册") - @PostMapping("api/userRegister") + @PostMapping("/api/userRegister") public Result userRegister(@Valid @RequestBody UserInfo userInfo) { return ResultFactory.buildSuccessResult(userInfoService.addUser(userInfo)); } @@ -44,7 +45,7 @@ public class UserInfoController { @ApiOperation("根据Id删除用户信息") @RequiresRoles(value = {"admin"}) - @GetMapping("api/deleteUser") + @GetMapping("/api/deleteUser") public Result deleteId(@RequestParam(value = "id") String id) { String[] gpIds = id.split(","); List list = new ArrayList<>(); @@ -57,7 +58,8 @@ public class UserInfoController { @ApiOperation("根据Id修改用户信息") - @PostMapping("api/updateUser") + @RequiresRoles(value = {"admin"}) + @PostMapping("/api/updateUser") public Result updateUser(@RequestBody UserInfo userInfo) { userInfoService.updateUser(userInfo); return ResultFactory.buildSuccessResult("更新成功"); @@ -65,22 +67,20 @@ public class UserInfoController { @ApiOperation("查询所有用户信息") - @RequiresRoles(value = {"admin"}) - @GetMapping("api/findAllUser") + @GetMapping("/api/findAllUser") public Result findAllUser() { return ResultFactory.buildSuccessResult(userInfoService.selectAll()); } @ApiOperation("根据用户名显示") - @RequiresRoles(value = {"admin"}) - @GetMapping("api/getUserByUsername") + @GetMapping("/api/getUserByUsername") public Result getUserByUsername(@RequestBody String username) { return ResultFactory.buildSuccessResult(userInfoService.selectByUsername(username)); } @ApiOperation("获取当前用户信息") - @GetMapping("api/getCurrentUserInfo") + @GetMapping("/api/getCurrentUserInfo") public Result getCurrentUserInfo(@RequestHeader(JwtUtils.AUTH_HEADER) String token) { return ResultFactory.buildSuccessResult(userInfoService .selectByUsername(jwtUtils.getCurrentUserInfo(token) @@ -88,17 +88,30 @@ public class UserInfoController { } @ApiOperation("用户修改密码") - @PostMapping("api/updatePassword") - public Result getCurrentUserInfo(@RequestBody UserInfo user, @RequestHeader(JwtUtils.AUTH_HEADER) String token) { - // 通过jwt获取当前用户 - // 修改当前用户密码 - UserInfo userInfo = userInfoService.findByUsername(jwtUtils.getCurrentUserInfo(token).getUsername()); - if (StringUtils.isEmpty(user) || StringUtils.isEmpty(user.getPassword())) { - return ResultFactory.buildFailResult("参数错误"); - } - userInfoService.updatePassword(userInfo.getId(), user.getPassword()); + @PostMapping("/api/updatePassword") + public Result getCurrentUserInfo(@RequestParam("password") @NotNull(message = "密码不能为空") String password, + @RequestHeader(JwtUtils.AUTH_HEADER) String token) { + userInfoService.updatePassword(JwtUtils.getUidByToken(token), password); return ResultFactory.buildSuccessResult("修改成功"); } + @ApiOperation("通过username获取密保问题") + @GetMapping("/api/getQuestion/{username}") + public Result getQuestion(@PathVariable String username) { + return ResultFactory.buildSuccessResult(userInfoService.getQuestion(username)); + } + + @ApiOperation("根据用户名和密保答案找回密码") + @PostMapping("/api/retrieve") + public Result retrieve(@RequestParam("answer") String answer, @RequestParam("username") String username) { + return ResultFactory.buildSuccessResult(userInfoService.retrieve(answer, username)); + } + + @ApiOperation("用户通过回执key修改密码") + @PostMapping("/api/updatePasswordByKey") + public Result updatePasswordByKey(@RequestParam("key") String key, @RequestParam("password") String password) { + userInfoService.updatePasswordByKey(key, password); + return ResultFactory.buildSuccessResult("修改成功"); + } } \ No newline at end of file diff --git a/src/main/java/com/zgn/fazhi/mapper/SecretGuardMapper.java b/src/main/java/com/zgn/fazhi/mapper/SecretGuardMapper.java new file mode 100644 index 0000000..60930c9 --- /dev/null +++ b/src/main/java/com/zgn/fazhi/mapper/SecretGuardMapper.java @@ -0,0 +1,16 @@ +package com.zgn.fazhi.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.zgn.fazhi.pojo.po.SecretGuard; +import org.springframework.stereotype.Repository; + +/** + * @author ydw + * @version 1.0 + * @Description TODO + * @date 20/08/2021 11:40 AM + */ + +@Repository +public interface SecretGuardMapper extends BaseMapper { +} diff --git a/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java b/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java index 693b967..fe421c6 100644 --- a/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java +++ b/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java @@ -38,4 +38,26 @@ public interface UserInfoMapper extends BaseMapper{ "where user_info.school_id=school.id and user_info.role_id=role.id and username=#{username}") UserInfoSchool ByName(@Param(value = "username") String username); + /** + * 根据用户名和密保答案查找用户id + * @param answer 密保答案 + * @param username 用户名 + * @return uid + */ + @Select("SELECT uid " + + "FROM user_info, user_secret " + + "WHERE username = #{username} AND answer = #{answer}") + Integer retrieve(@Param(value = "answer")String answer, @Param(value = "username")String username); + + /** + * 通过用户名查找该用户的密保问题 + * @param username 用户名 + * @return 密保问题 + */ + @Select("SELECT problem " + + "FROM secret_guard AS g INNER JOIN user_secret AS s ON g.id = s.secret_id " + + "INNER JOIN user_info AS u ON u.id = s.uid " + + "WHERE username = #{username}") + String getQuestion(@Param(value = "username") String username); + } diff --git a/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java b/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java index 1af9cdb..55bbd10 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java @@ -3,19 +3,26 @@ package com.zgn.fazhi.pojo.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import javax.validation.constraints.NotNull; import java.io.Serializable; /** * 密保问题 */ +@Data +@Accessors(chain = true) public class SecretGuard implements Serializable { private static final long serialVersionUID = 1L; + @NotNull @TableId(value = "id", type = IdType.AUTO) private Integer id; + @NotNull @ApiModelProperty(value = "密保问题") private String problem; diff --git a/src/main/java/com/zgn/fazhi/service/SecretGuardService.java b/src/main/java/com/zgn/fazhi/service/SecretGuardService.java new file mode 100644 index 0000000..696ff1f --- /dev/null +++ b/src/main/java/com/zgn/fazhi/service/SecretGuardService.java @@ -0,0 +1,14 @@ +package com.zgn.fazhi.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.zgn.fazhi.pojo.po.SecretGuard; + +/** + * @author ydw + * @version 1.0 + * @Description TODO + * @date 20/08/2021 11:42 AM + */ + +public interface SecretGuardService extends IService { +} diff --git a/src/main/java/com/zgn/fazhi/service/UserInfoService.java b/src/main/java/com/zgn/fazhi/service/UserInfoService.java index bd5231b..d7903d7 100644 --- a/src/main/java/com/zgn/fazhi/service/UserInfoService.java +++ b/src/main/java/com/zgn/fazhi/service/UserInfoService.java @@ -80,4 +80,27 @@ public interface UserInfoService extends IService { */ UserInfo findByUid(Integer uid); + /** + * 根据密保答案和用户名找回密码 + * @param answer 密保答案 + * @param username 用户名 + * @return + */ + String retrieve(String answer, String username); + + /** + * 通过回调key修改密码 + * @param key key + * @param password 密码 + * @return + */ + Boolean updatePasswordByKey(String key, String password); + + /** + * 通过用户名获取密保问题 + * @param username 用户名 + * @return 密保问题 + */ + String getQuestion(String username); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/SecretGuardServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/SecretGuardServiceImpl.java new file mode 100644 index 0000000..1059303 --- /dev/null +++ b/src/main/java/com/zgn/fazhi/service/impl/SecretGuardServiceImpl.java @@ -0,0 +1,21 @@ +package com.zgn.fazhi.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.zgn.fazhi.mapper.SecretGuardMapper; +import com.zgn.fazhi.pojo.po.SecretGuard; +import com.zgn.fazhi.service.SecretGuardService; +import org.springframework.stereotype.Service; + +/** + * @author ydw + * @version 1.0 + * @description TODO + * @date 20/08/2021 11:42 AM + */ + +@Service +public class SecretGuardServiceImpl extends ServiceImpl implements SecretGuardService { + + + +} diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java index 586a242..3216ced 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java @@ -30,6 +30,7 @@ import org.springframework.util.StringUtils; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; /** *

@@ -72,11 +73,13 @@ public class UserInfoServiceImpl extends ServiceImpl i // 没有用户名邮箱、手机号唯一标识,需要手动生成用户名返回给用户 String password = user.getPassword(); - // 生成六位数作为用户名 - String username; - do { - username = stringUtils.getRandomUsername(); - } while (!StringUtils.isEmpty(findByUsername(username))); + String username = user.getUsername(); + if (StringUtils.isEmpty(username)){ + // 如果username为空则生成六位数作为用户名 + do { + username = stringUtils.getRandomUsername(); + } while (!StringUtils.isEmpty(findByUsername(username))); + } // 生成16位数随机盐,注册时进行盐值加密 String salt = new SecureRandomNumberGenerator().nextBytes().toString(); @@ -301,4 +304,33 @@ public class UserInfoServiceImpl extends ServiceImpl i redisUtil.set(KEY + uid, userInfo, RedisUtil.EXPIRETIME); return userInfo; } + + @Override + public String retrieve(String answer, String username) { + Integer uid = userMapper.retrieve(answer, username); + if (StringUtils.isEmpty(uid)){ + throw new RestException(400, "验证信息错误"); + } + // 生成密钥保存redis 并返回 + String key = "RETRIEVE@" + ThreadLocalRandom.current().nextInt(10086); + // 设置有效期5分钟 + redisUtil.set(key, uid, 5 * 60); + return key; + } + + @Override + public Boolean updatePasswordByKey(String key, String password) { + Object o = redisUtil.get(key); + if (StringUtils.isEmpty(o)){ + throw new RestException(400, "密钥无效"); + } + int uid = Integer.parseInt(o.toString()); + userMapper.updateById(new UserInfo().setPassword(password).setId(uid)); + return true; + } + + @Override + public String getQuestion(String username) { + return userMapper.getQuestion(username); + } } diff --git a/src/test/java/com/zgn/fazhi/service/impl/SecretGuardServiceImplTest.java b/src/test/java/com/zgn/fazhi/service/impl/SecretGuardServiceImplTest.java new file mode 100644 index 0000000..a06fb74 --- /dev/null +++ b/src/test/java/com/zgn/fazhi/service/impl/SecretGuardServiceImplTest.java @@ -0,0 +1,26 @@ +package com.zgn.fazhi.service.impl; + +import com.zgn.fazhi.service.SecretGuardService; +import com.zgn.fazhi.service.UserInfoService; +import lombok.experimental.Accessors; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@Slf4j +class SecretGuardServiceImplTest { + + @Autowired + private UserInfoService userInfoService; + + @Test + void test1(){ + String admin = userInfoService.getQuestion("admin"); + log.info("admin密保: {}", admin); + } + +} \ No newline at end of file -- Gitee From 86c0a31f4ec9829ad962ee6111b929cc89a7d12a Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Fri, 20 Aug 2021 19:20:27 +0800 Subject: [PATCH 11/13] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=AF=B9=E8=80=83?= =?UTF-8?q?=E8=AF=95=E7=BB=83=E4=B9=A0=E6=9D=83=E9=99=90=E5=A2=9E=E5=88=A0?= =?UTF-8?q?=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExaminationPermissionController.java | 11 +++- .../controller/SecretGuardController.java | 8 ++- .../java/com/zgn/fazhi/filter/JwtFilter.java | 19 +++--- .../mapper/ExaminationPermissionMapper.java | 31 ++++++++++ .../java/com/zgn/fazhi/pojo/po/ClassInfo.java | 2 + .../com/zgn/fazhi/pojo/po/SecretGuard.java | 1 - .../java/com/zgn/fazhi/pojo/po/UserGrade.java | 2 + .../java/com/zgn/fazhi/pojo/po/WebInfo.java | 2 + .../zgn/fazhi/pojo/vo/ExaPermissionVo.java | 43 +++++++++++++ .../fazhi/pojo/vo/ExaPermissionVoList.java | 38 ++++++++++++ .../java/com/zgn/fazhi/realm/JwtRealm.java | 4 +- .../java/com/zgn/fazhi/realm/ShiroRealm.java | 21 ++----- .../java/com/zgn/fazhi/result/ResultCode.java | 19 ++++++ .../service/ExaminationPermissionService.java | 6 +- .../ExaminationPermissionServiceImpl.java | 61 +++++++++++++++++-- .../service/impl/WebInfoServiceImpl.java | 34 +++++------ .../ExaminationPermissionServiceImplTest.java | 27 ++++++++ .../ExaminationRecordServiceImplTest.java | 2 +- 18 files changed, 271 insertions(+), 60 deletions(-) create mode 100644 src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVo.java create mode 100644 src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVoList.java create mode 100644 src/test/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImplTest.java diff --git a/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java b/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java index 87a78af..6097cee 100644 --- a/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java +++ b/src/main/java/com/zgn/fazhi/controller/ExaminationPermissionController.java @@ -12,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; +import java.util.List; /** * 考试/练习权限控制 @@ -34,8 +35,14 @@ public class ExaminationPermissionController { @ApiOperation("通过考试练习id查询开放权限") @GetMapping("/admin/getExaPermission/{rid}") public Result getExaPermission(@PathVariable Integer rid) { -// permissionService.getExaPermission(exaPermission); - return ResultFactory.buildSuccessResult("操作成功"); + return ResultFactory.buildSuccessResult(permissionService.getExaPermissionByRid(rid)); + } + + @ApiOperation("批量删除权限") + @RequiresRoles(value = {"admin", "teacher"}, logical = Logical.OR) + @PostMapping("/admin/delExaPermission") + public Result delExaPermission(@RequestBody List idList) { + return ResultFactory.buildSuccessResult(permissionService.delExaPermissionById(idList)); } } diff --git a/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java b/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java index 460792d..d64a9e2 100644 --- a/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java +++ b/src/main/java/com/zgn/fazhi/controller/SecretGuardController.java @@ -6,6 +6,8 @@ import com.zgn.fazhi.result.Result; import com.zgn.fazhi.service.SecretGuardService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.Logical; +import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -26,19 +28,22 @@ public class SecretGuardController { private SecretGuardService secretGuardService; @ApiOperation("查询所有密保问题") + @RequiresRoles(value = {"admin"}) @GetMapping("/api/getSecretGuard") public Result getSecretGuard() { return ResultFactory.buildSuccessResult(secretGuardService.list()); } @ApiOperation("增加密保问题") + @RequiresRoles(value = {"admin"}) @PostMapping("/api/saveSecretGuard") - public Result addSecretGuard(@RequestBody SecretGuard secretGuard) { + public Result addSecretGuard(@RequestBody @Valid SecretGuard secretGuard) { secretGuardService.save(secretGuard); return ResultFactory.buildSuccessResult("添加成功"); } @ApiOperation("根据id删除密保问题") + @RequiresRoles(value = {"admin"}) @PostMapping("/api/delSecretGuard") public Result delSecretGuard(@RequestParam("id") Integer id){ secretGuardService.removeById(id); @@ -46,6 +51,7 @@ public class SecretGuardController { } @ApiOperation("根据id更新密保问题") + @RequiresRoles(value = {"admin"}) @PostMapping("/api/updateSecretGuard") public Result updateSecretGuard(@RequestBody @Valid SecretGuard secretGuard){ secretGuardService.updateById(secretGuard); diff --git a/src/main/java/com/zgn/fazhi/filter/JwtFilter.java b/src/main/java/com/zgn/fazhi/filter/JwtFilter.java index 1ca47c5..6138449 100644 --- a/src/main/java/com/zgn/fazhi/filter/JwtFilter.java +++ b/src/main/java/com/zgn/fazhi/filter/JwtFilter.java @@ -31,11 +31,9 @@ public class JwtFilter extends BasicHttpAuthenticationFilter { */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { - HttpServletRequest httpServletRequest = WebUtils.toHttp(request); - HttpServletResponse httpServletResponse = WebUtils.toHttp(response); // 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态 - if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { - httpServletResponse.setStatus(HttpStatus.OK.value()); + if (WebUtils.toHttp(request).getMethod().equals(RequestMethod.OPTIONS.name())) { + WebUtils.toHttp(response).setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); @@ -115,8 +113,8 @@ public class JwtFilter extends BasicHttpAuthenticationFilter { protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String authorization = httpServletRequest.getHeader(JwtUtils.AUTH_HEADER); - log.info("当前token: {}", authorization); - log.info("当前签名的uid: {}", JwtUtils.getClaimFiled(authorization, "uid")); + log.debug("当前token: {}", authorization); + log.debug("当前签名的uid: {}", JwtUtils.getClaimFiled(authorization, "uid")); JwtToken token = new JwtToken(authorization); log.debug("从请求头获取token:{}", token); return token; @@ -132,7 +130,7 @@ public class JwtFilter extends BasicHttpAuthenticationFilter { httpResponse.setContentType("application/json;charset=UTF-8"); httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); PrintWriter writer = httpResponse.getWriter(); - writer.write("{\"errCode\": 401, \"msg\": \"UNAUTHORIZED\"}"); + writer.write("{\"errCode\": 401, \"msg\": \"请登陆认证\"}"); fillCorsHeader(WebUtils.toHttp(servletRequest), httpResponse); return false; } @@ -143,15 +141,14 @@ public class JwtFilter extends BasicHttpAuthenticationFilter { */ @Override protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, - ServletResponse response) throws Exception { - HttpServletResponse httpResponse = WebUtils.toHttp(response); + ServletResponse response) { String newToken = null; if (token instanceof JwtToken) { newToken = JwtUtils.refreshTokenExpired(token.getCredentials().toString(), JwtUtils.SECRET); } - if (newToken != null){ + if (newToken != null) { log.debug("jwt认证成功,返回刷新后的token:{}", newToken); - httpResponse.setHeader(JwtUtils.AUTH_HEADER, newToken); + WebUtils.toHttp(response).setHeader(JwtUtils.AUTH_HEADER, newToken); } return true; diff --git a/src/main/java/com/zgn/fazhi/mapper/ExaminationPermissionMapper.java b/src/main/java/com/zgn/fazhi/mapper/ExaminationPermissionMapper.java index 2c18f69..7978474 100644 --- a/src/main/java/com/zgn/fazhi/mapper/ExaminationPermissionMapper.java +++ b/src/main/java/com/zgn/fazhi/mapper/ExaminationPermissionMapper.java @@ -2,11 +2,42 @@ package com.zgn.fazhi.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zgn.fazhi.pojo.po.ExaminationPermission; +import com.zgn.fazhi.pojo.vo.ExaPermissionVo; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; +import java.util.List; + /** * @author ydw */ @Repository public interface ExaminationPermissionMapper extends BaseMapper { + + @Select("SELECT p.id, record_id, p.school_id, school_name, p.grade_id, grade_name, p.class_id, class_name " + + "FROM examination_permission AS p INNER JOIN school AS s ON p.school_id = s.id " + + "INNER JOIN user_grade AS g ON p.grade_id = g.id " + + "INNER JOIN class_info AS c ON p.class_id = c.id " + + "WHERE p.record_id = #{rid}") + List selectVoList(@Param("rid") Integer rid); + + @Select("SELECT p.id, record_id, p.school_id, school_name, p.grade_id, grade_name, p.class_id, class_name " + + "FROM examination_permission AS p INNER JOIN school AS s ON p.school_id = s.id " + + "INNER JOIN user_grade AS g ON p.grade_id = g.id " + + "INNER JOIN class_info AS c ON p.class_id = c.id " + + "WHERE p.record_id = #{rid}") + List selectVoClassList(@Param("rid") Integer rid); + + @Select("SELECT p.id, record_id, p.school_id, school_name, p.grade_id, grade_name " + + "FROM examination_permission AS p INNER JOIN school AS s ON p.school_id = s.id " + + "INNER JOIN user_grade AS g ON p.grade_id = g.id " + + "WHERE p.record_id = #{rid} AND p.class_id IS NULL") + List selectVoGradeList(@Param("rid") Integer rid); + + @Select("SELECT p.id, record_id, p.school_id, school_name " + + "FROM examination_permission AS p INNER JOIN school AS s ON p.school_id = s.id " + + "WHERE p.record_id = #{rid} AND p.grade_id IS NULL") + List selectVoSchoolList(@Param("rid") Integer rid); + } diff --git a/src/main/java/com/zgn/fazhi/pojo/po/ClassInfo.java b/src/main/java/com/zgn/fazhi/pojo/po/ClassInfo.java index d0dc648..6fc974f 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/ClassInfo.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/ClassInfo.java @@ -1,6 +1,7 @@ package com.zgn.fazhi.pojo.po; import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @@ -24,6 +25,7 @@ public class ClassInfo implements Serializable { private Integer id; @NotNull(message = "班级名称不能为空") + @TableField(value = "class_name") @ApiModelProperty(value = "班级名称") private String name; diff --git a/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java b/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java index 55bbd10..0fb66c8 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/SecretGuard.java @@ -18,7 +18,6 @@ public class SecretGuard implements Serializable { private static final long serialVersionUID = 1L; - @NotNull @TableId(value = "id", type = IdType.AUTO) private Integer id; diff --git a/src/main/java/com/zgn/fazhi/pojo/po/UserGrade.java b/src/main/java/com/zgn/fazhi/pojo/po/UserGrade.java index 45cfbe3..1d6f90a 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/UserGrade.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/UserGrade.java @@ -1,6 +1,7 @@ package com.zgn.fazhi.pojo.po; import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @@ -23,6 +24,7 @@ public class UserGrade implements Serializable { private Integer id; @NotNull(message = "年级名称不能为空") + @TableField(value = "grade_name") @ApiModelProperty(value = "年级名称") private String name; diff --git a/src/main/java/com/zgn/fazhi/pojo/po/WebInfo.java b/src/main/java/com/zgn/fazhi/pojo/po/WebInfo.java index 642864f..38ce351 100644 --- a/src/main/java/com/zgn/fazhi/pojo/po/WebInfo.java +++ b/src/main/java/com/zgn/fazhi/pojo/po/WebInfo.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; /** *

@@ -19,6 +20,7 @@ import lombok.EqualsAndHashCode; */ @Data @EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) @ApiModel(value="WebInfo对象", description="") public class WebInfo implements Serializable { diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVo.java b/src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVo.java new file mode 100644 index 0000000..2269ffe --- /dev/null +++ b/src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVo.java @@ -0,0 +1,43 @@ +package com.zgn.fazhi.pojo.vo; + +import com.baomidou.mybatisplus.annotation.TableField; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author ydw + * @version 1.0 + * @description TODO + * @date 20/08/2021 5:23 PM + */ + +@Data +@Accessors(chain = true) +public class ExaPermissionVo implements Serializable { + + private static final long serialVersionUID = 1L; + + private Integer id; + + @ApiModelProperty(value = "记录id") + private Integer recordId; + + @ApiModelProperty(value = "学校id") + private Integer schoolId; + + private String schoolName; + + @ApiModelProperty(value = "年级id") + private Integer gradeId; + + private String gradeName; + + @ApiModelProperty(value = "班级id") + private Integer classId; + + private String className; + +} diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVoList.java b/src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVoList.java new file mode 100644 index 0000000..6645549 --- /dev/null +++ b/src/main/java/com/zgn/fazhi/pojo/vo/ExaPermissionVoList.java @@ -0,0 +1,38 @@ +package com.zgn.fazhi.pojo.vo; + +import com.zgn.fazhi.pojo.po.ExaminationPermission; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * @author ydw + * @version 1.0 + * @description 考试练习权限开放 + * @date 20/08/2021 4:14 PM + */ + +@Data +@Accessors(chain = true) +public class ExaPermissionVoList implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 开放等级为学校列表 + */ + private List schoolList; + + /** + * 开放等级为年级列表 + */ + private List gradeList; + + /** + * 开放等级为班级列表 + */ + private List classList; + +} diff --git a/src/main/java/com/zgn/fazhi/realm/JwtRealm.java b/src/main/java/com/zgn/fazhi/realm/JwtRealm.java index 998f2c0..610f2de 100644 --- a/src/main/java/com/zgn/fazhi/realm/JwtRealm.java +++ b/src/main/java/com/zgn/fazhi/realm/JwtRealm.java @@ -64,9 +64,9 @@ public class JwtRealm extends AuthorizingRealm { // 获取当前用户 // 查询数据库,获取用户的角色信息 Set roles = new HashSet<>(); - log.info("通过用户角色id查询角色名称"); + log.debug("通过用户角色id查询角色名称"); String roleName = roleService.findRnameByUid(Integer.parseInt(principals.getPrimaryPrincipal().toString())); - log.info("当前角色 : " + roleName); + log.debug("当前角色 : " + roleName); roles.add(roleName); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setRoles(roles); diff --git a/src/main/java/com/zgn/fazhi/realm/ShiroRealm.java b/src/main/java/com/zgn/fazhi/realm/ShiroRealm.java index 9263712..da46c80 100644 --- a/src/main/java/com/zgn/fazhi/realm/ShiroRealm.java +++ b/src/main/java/com/zgn/fazhi/realm/ShiroRealm.java @@ -22,6 +22,7 @@ import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; /** @@ -35,9 +36,6 @@ public class ShiroRealm extends AuthorizingRealm { @Autowired private UserInfoMapper userMapper; - @Autowired - private RoleMapper roleMapper; - /** * 限定这个 Realm 只处理 UsernamePasswordToken */ @@ -55,26 +53,17 @@ public class ShiroRealm extends AuthorizingRealm { String username = (String) token.getPrincipal(); // 查询数据库获取用户信息 - QueryWrapper userKeyQueryWrapper = new QueryWrapper<>(); - userKeyQueryWrapper.eq("username", username); - UserInfo user = userMapper.selectOne(userKeyQueryWrapper); + UserInfo user = userMapper.selectOne( + new QueryWrapper().eq("username", username)); // 用户不存在 - if (user == null) { + if (StringUtils.isEmpty(user)) { throw new UnknownAccountException("用户不存在!"); } - - // 用户被锁定 -// if (user.getLocked()) { -// throw new LockedAccountException("该用户已被锁定,暂时无法登录!"); -// } log.debug("正在通过shiro原生token登陆认证"); // 如果存在该用户,获取其加密后的密码以及盐值 - String password = user.getPassword(); - String salt = user.getSalt(); - - return new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt), getName()); + return new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName()); } /** diff --git a/src/main/java/com/zgn/fazhi/result/ResultCode.java b/src/main/java/com/zgn/fazhi/result/ResultCode.java index 923985d..0796d51 100644 --- a/src/main/java/com/zgn/fazhi/result/ResultCode.java +++ b/src/main/java/com/zgn/fazhi/result/ResultCode.java @@ -2,10 +2,29 @@ package com.zgn.fazhi.result; public enum ResultCode { + /** + * 成功 + */ SUCCESS(200), + + /** + * 失败 + */ FAIL(400), + + /** + * 未认证 + */ UNAUTHORIZED(401), + + /** + * 未找到 + */ NOT_FOUND(404), + + /** + * 服务器内部错误 + */ INTERNAL_SERVER_ERROR(500); public int code; diff --git a/src/main/java/com/zgn/fazhi/service/ExaminationPermissionService.java b/src/main/java/com/zgn/fazhi/service/ExaminationPermissionService.java index 10162c2..efd99ae 100644 --- a/src/main/java/com/zgn/fazhi/service/ExaminationPermissionService.java +++ b/src/main/java/com/zgn/fazhi/service/ExaminationPermissionService.java @@ -3,6 +3,8 @@ package com.zgn.fazhi.service; import com.baomidou.mybatisplus.extension.service.IService; import com.zgn.fazhi.pojo.po.ExaminationPermission; import com.zgn.fazhi.pojo.vo.ExaPermission; +import com.zgn.fazhi.pojo.vo.ExaPermissionVo; +import com.zgn.fazhi.pojo.vo.ExaPermissionVoList; import java.util.List; @@ -13,6 +15,8 @@ public interface ExaminationPermissionService extends IService idList); + /** * 查询开放级别为学校级别 * @param schoolId 学校id @@ -40,6 +44,6 @@ public interface ExaminationPermissionService extends IService getExaPermissionByRid(Integer rid); + ExaPermissionVoList getExaPermissionByRid(Integer rid); } diff --git a/src/main/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImpl.java index befa768..7879a31 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImpl.java @@ -1,15 +1,21 @@ package com.zgn.fazhi.service.impl; +import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zgn.fazhi.exception.RestException; import com.zgn.fazhi.mapper.ExaminationPermissionMapper; import com.zgn.fazhi.pojo.po.ExaminationPermission; import com.zgn.fazhi.pojo.vo.ExaPermission; +import com.zgn.fazhi.pojo.vo.ExaPermissionVo; +import com.zgn.fazhi.pojo.vo.ExaPermissionVoList; import com.zgn.fazhi.pojo.vo.OpenRestriction; import com.zgn.fazhi.service.ExaminationPermissionService; +import com.zgn.fazhi.utils.FastJsonUtils; +import com.zgn.fazhi.utils.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -18,6 +24,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author ydw @@ -29,6 +36,11 @@ public class ExaminationPermissionServiceImpl extends ServiceImpl permission = exaPermission.getPermission(); @@ -69,6 +81,24 @@ public class ExaminationPermissionServiceImpl extends ServiceImpl idList) { + // 清理缓存 + try { + permissionMapper.selectBatchIds(idList) + .stream() + .map(ExaminationPermission::getRecordId) + .distinct() + .collect(Collectors.toList()) + .forEach(rid -> redisUtil.del(KEY + rid)); + } catch (NullPointerException e){ + e.printStackTrace(); + } + permissionMapper.deleteBatchIds(idList); return true; } @@ -108,10 +138,31 @@ public class ExaminationPermissionServiceImpl extends ServiceImpl getExaPermissionByRid(Integer rid) { - return permissionMapper.selectList( - new QueryWrapper() - .eq("record_id", rid) - ); + public ExaPermissionVoList getExaPermissionByRid(Integer rid) { + String key = KEY + rid; + try { + if (redisUtil.hasKey(key)) { + return FastJsonUtils.toBean(redisUtil.get(KEY), ExaPermissionVoList.class); + } + } catch (RedisConnectionFailureException e) { + return getExaPermissionVo(rid); + } + ExaPermissionVoList exaPermissionVo = getExaPermissionVo(rid); + redisUtil.setIfAbsent(key, exaPermissionVo, RedisUtil.EXPIRETIME); + return exaPermissionVo; } + + private ExaPermissionVoList getExaPermissionVo(Integer rid) { + // 分组 + ExaPermissionVoList exaPermissionVoList = new ExaPermissionVoList(); + // class + exaPermissionVoList.setClassList(permissionMapper.selectVoClassList(rid)); + // grade + exaPermissionVoList.setGradeList(permissionMapper.selectVoGradeList(rid)); + // school + exaPermissionVoList.setSchoolList(permissionMapper.selectVoSchoolList(rid)); + log.info(JSON.toJSONString(exaPermissionVoList)); + return exaPermissionVoList; + } + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/WebInfoServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/WebInfoServiceImpl.java index b6403ab..3eea1b2 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/WebInfoServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/WebInfoServiceImpl.java @@ -7,6 +7,7 @@ import com.zgn.fazhi.mapper.WebInfoMapper; import com.zgn.fazhi.service.WebInfoService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zgn.fazhi.utils.RedisUtil; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -14,28 +15,26 @@ import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; +import java.util.concurrent.ThreadLocalRandom; + /** *

- * 服务实现类 + * 服务实现类 *

* * @author wt * @since 2021-06-25 */ @Service +@Slf4j public class WebInfoServiceImpl extends ServiceImpl implements WebInfoService { - private static final Logger LOGGER = LoggerFactory.getLogger(WebInfoServiceImpl.class); - @Autowired private WebInfoMapper webInfoMapper; @Autowired private RedisUtil redisUtil; - @Autowired - private RedisTemplate redisTemplate; - @Override public WebInfo getWebInfo() { return webInfoMapper.selectOne(null); @@ -43,22 +42,26 @@ public class WebInfoServiceImpl extends ServiceImpl impl @Override public Boolean saveWebInfo(Integer views) { - WebInfo webInfo = getWebInfo(); - webInfo.setTimes(views); - webInfoMapper.updateById(webInfo); + webInfoMapper.updateById( + getWebInfo().setTimes(views)); return true; } /** * 访问人数自增 + * * @return 返回访问人数 */ @Override public Integer incr() { try { - redisTemplate.opsForValue().get("views"); + // 访问人数递增1 ~ 3 + Integer views = (int) redisUtil.incr("views", ThreadLocalRandom.current().nextInt(1, 4)); + if ((views % 75) <= 3) { + saveWebInfo(views); + } + return views; } catch (RedisConnectionFailureException e) { - LOGGER.error("redis连接错误,正在连接数据库做访问人数自增: " + e.toString()); // 如果redis挂掉,向数据库查询访问人数并自增 WebInfo webInfo = getWebInfo(); Integer views = webInfo.getTimes(); @@ -66,14 +69,5 @@ public class WebInfoServiceImpl extends ServiceImpl impl saveWebInfo(views); return views; } - - // 访问人数递增1 - redisUtil.incr("views", 1); - Integer views = (Integer) redisUtil.get("views"); - if ((views % 66) == 0) { - // 如果为66的倍数,写入到数据库中 - saveWebInfo(views); - } - return views; } } diff --git a/src/test/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImplTest.java b/src/test/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImplTest.java new file mode 100644 index 0000000..8a6353e --- /dev/null +++ b/src/test/java/com/zgn/fazhi/service/impl/ExaminationPermissionServiceImplTest.java @@ -0,0 +1,27 @@ +package com.zgn.fazhi.service.impl; + +import com.alibaba.fastjson.JSON; +import com.zgn.fazhi.pojo.vo.ExaPermissionVoList; +import com.zgn.fazhi.service.ExaminationPermissionService; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@Slf4j +class ExaminationPermissionServiceImplTest { + + @Autowired + private ExaminationPermissionService examinationPermissionService; + + @Test + void getExaPermissionByRid() { + ExaPermissionVoList exaPermissionByRid = examinationPermissionService.getExaPermissionByRid(5); + System.out.println(JSON.toJSON(exaPermissionByRid.getSchoolList())); + System.out.println(JSON.toJSON(exaPermissionByRid.getGradeList())); + System.out.println(JSON.toJSON(exaPermissionByRid.getClassList())); + } +} \ No newline at end of file diff --git a/src/test/java/com/zgn/fazhi/service/impl/ExaminationRecordServiceImplTest.java b/src/test/java/com/zgn/fazhi/service/impl/ExaminationRecordServiceImplTest.java index 2957cb0..5904429 100644 --- a/src/test/java/com/zgn/fazhi/service/impl/ExaminationRecordServiceImplTest.java +++ b/src/test/java/com/zgn/fazhi/service/impl/ExaminationRecordServiceImplTest.java @@ -127,7 +127,7 @@ class ExaminationRecordServiceImplTest { @Test void getRecordPermission() { // 开放学校id 4 - examinationPermissionService.getExaPermissionByRid(5).forEach(System.out::println); +// examinationPermissionService.getExaPermissionByRid(5).forEach(System.out::println); } /** -- Gitee From f452b6d600bf4e60900c84641422a138e6f6af32 Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Fri, 20 Aug 2021 22:05:55 +0800 Subject: [PATCH 12/13] =?UTF-8?q?=E8=B0=83=E6=95=B4=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E8=80=83=E8=AF=95=E7=BB=83=E4=B9=A0=E6=88=90?= =?UTF-8?q?=E7=BB=A9=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UserExaminationScoreController.java | 12 +++++--- .../mapper/UserExaminationScoreMapper.java | 28 +++++++++++++++++++ .../com/zgn/fazhi/pojo/vo/UserExaGrade.java | 28 +++++++++++++++++++ .../service/UserExaminationScoreService.java | 6 ++++ .../impl/UserExaminationScoreServiceImpl.java | 28 ++++--------------- .../UserExaminationScoreServiceImplTest.java | 7 +++-- 6 files changed, 81 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java b/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java index 769878d..8b4eee0 100644 --- a/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java +++ b/src/main/java/com/zgn/fazhi/controller/UserExaminationScoreController.java @@ -17,9 +17,6 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class UserExaminationScoreController { - @Autowired - private JwtUtils jwtUtils; - @Autowired private UserExaminationScoreService userExaminationScoreService; @@ -27,8 +24,15 @@ public class UserExaminationScoreController { @GetMapping("/api/getCurrentExaDate/{rid}") public Result getCurrentExaDate(@RequestHeader(JwtUtils.AUTH_HEADER) String token, @PathVariable Integer rid) { return ResultFactory.buildSuccessResult( - userExaminationScoreService.getCurrentExaDateByUid(jwtUtils.getCurrentUserInfo(token).getId(), rid)); + userExaminationScoreService.getCurrentExaDateByUid(JwtUtils.getUidByToken(token), rid)); } + @ApiOperation("当前用户查询历次考试练习的成绩") + @GetMapping("/api/getCurrentExaDateList/{rid}") + public Result getCurrentExaDateList(@RequestHeader(JwtUtils.AUTH_HEADER) String token){ + return ResultFactory.buildSuccessResult( + userExaminationScoreService.getCurrentExaDateListByUid(JwtUtils.getUidByToken(token))); + } + } diff --git a/src/main/java/com/zgn/fazhi/mapper/UserExaminationScoreMapper.java b/src/main/java/com/zgn/fazhi/mapper/UserExaminationScoreMapper.java index 8e4150b..d7b8a47 100644 --- a/src/main/java/com/zgn/fazhi/mapper/UserExaminationScoreMapper.java +++ b/src/main/java/com/zgn/fazhi/mapper/UserExaminationScoreMapper.java @@ -2,9 +2,14 @@ package com.zgn.fazhi.mapper; import com.zgn.fazhi.pojo.po.UserExaminationScore; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.zgn.fazhi.pojo.vo.UserExaGrade; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; +import java.util.List; + /** *

* Mapper 接口 @@ -16,4 +21,27 @@ import org.springframework.stereotype.Repository; @Repository public interface UserExaminationScoreMapper extends BaseMapper { + + /** + * 查询用户历次所有考试练习成绩 + * @param uid 用户id + * @return 成绩表 + */ + @Select("SELECT record_id, title, achievement1 AS score, ue.start, ue.end, UNIX_TIMESTAMP(ue.end) - UNIX_TIMESTAMP(ue.start) AS time_length " + + "FROM user_examination AS ue INNER JOIN examination_record AS r ON ue.record_id = r.id " + + "WHERE ue.uid = #{uid}") + List getCurrentExaDateListByUid(@Param("uid") Integer uid); + + + /** + * 查询该次考试练习的成绩 + * @param uid 用户id + * @param rid 开始记录id + * @return 成绩表 + */ + @Select("SELECT record_id, title, achievement1 AS score, ue.start, ue.end, UNIX_TIMESTAMP(ue.end) - UNIX_TIMESTAMP(ue.start) AS time_length " + + "FROM user_examination AS ue INNER JOIN examination_record AS r ON ue.record_id = r.id " + + "WHERE ue.uid = #{uid} AND ue.record_id = #{rid}") + List getCurrentExaDateByUid(@Param("uid") Integer uid, @Param("rid") Integer rid); + } diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/UserExaGrade.java b/src/main/java/com/zgn/fazhi/pojo/vo/UserExaGrade.java index 700b60f..f2f32cc 100644 --- a/src/main/java/com/zgn/fazhi/pojo/vo/UserExaGrade.java +++ b/src/main/java/com/zgn/fazhi/pojo/vo/UserExaGrade.java @@ -1,9 +1,11 @@ package com.zgn.fazhi.pojo.vo; +import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; +import java.util.Date; /** * 封装单个用户的成绩实体类 @@ -14,8 +16,34 @@ public class UserExaGrade implements Serializable { private static final long serialVersionUID = 1L; + /** + * 考试练习id + */ + private Integer recordId; + + /** + * 考试练习标题 + */ + private String title; + + /** + * 总分 + */ private Integer score; + /** + * 开始考试时间 + */ + private Date start; + + /** + * 结束考试时间 + */ + private Date end; + + /** + * 考试时长 + */ private Integer timeLength; } diff --git a/src/main/java/com/zgn/fazhi/service/UserExaminationScoreService.java b/src/main/java/com/zgn/fazhi/service/UserExaminationScoreService.java index 034f943..26ddd38 100644 --- a/src/main/java/com/zgn/fazhi/service/UserExaminationScoreService.java +++ b/src/main/java/com/zgn/fazhi/service/UserExaminationScoreService.java @@ -24,4 +24,10 @@ public interface UserExaminationScoreService extends IService getCurrentExaDateByUid(Integer uid, Integer rid); + /** + * 获取当前用户历次所有考试成绩 + * @return + */ + List getCurrentExaDateListByUid(Integer uid); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImpl.java index 973c7b1..ace60a5 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImpl.java @@ -1,17 +1,13 @@ package com.zgn.fazhi.service.impl; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.zgn.fazhi.pojo.po.UserExamination; import com.zgn.fazhi.pojo.po.UserExaminationScore; import com.zgn.fazhi.mapper.UserExaminationScoreMapper; import com.zgn.fazhi.pojo.vo.UserExaGrade; import com.zgn.fazhi.service.UserExaminationScoreService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.zgn.fazhi.service.UserExaminationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.ArrayList; import java.util.List; /** @@ -28,9 +24,6 @@ public class UserExaminationScoreServiceImpl extends ServiceImpl getCurrentExaDateByUid(Integer uid, Integer rid) { - List userExaGrades = new ArrayList<>(); - try { - userExaminationService.findAllByUid(uid, rid) - .forEach(userExamination1 -> { - UserExaGrade userExaGrade = new UserExaGrade(); - userExaGrade.setScore(userExamination1.getAchievement1()) - .setTimeLength( - (int) (userExamination1.getEnd().getTime() - userExamination1.getStart().getTime())); - userExaGrades.add(userExaGrade); - }); - } catch (NullPointerException e){ - // 没有成绩返回null - return null; - } - return userExaGrades; + return userExaminationScoreMapper.getCurrentExaDateByUid(uid, rid); + } + + @Override + public List getCurrentExaDateListByUid(Integer uid) { + return userExaminationScoreMapper.getCurrentExaDateListByUid(uid); } } diff --git a/src/test/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImplTest.java b/src/test/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImplTest.java index b2be94c..5c83783 100644 --- a/src/test/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImplTest.java +++ b/src/test/java/com/zgn/fazhi/service/impl/UserExaminationScoreServiceImplTest.java @@ -23,9 +23,12 @@ class UserExaminationScoreServiceImplTest { */ @Test void getCurrentExaDateByUid() { - - List currentExaDateByUid = userExaminationScoreService.getCurrentExaDateByUid(34, 5); + List currentExaDateByUid = userExaminationScoreService.getCurrentExaDateByUid(1, 4); currentExaDateByUid.forEach(System.out::println); + } + @Test + void getCurrentExaDateListByUid(){ + userExaminationScoreService.getCurrentExaDateListByUid(1).forEach(System.out::println); } } \ No newline at end of file -- Gitee From ef180275926d1220501df417d317c4fd4637e52e Mon Sep 17 00:00:00 2001 From: zgn <1215577830@qq.com> Date: Fri, 20 Aug 2021 23:29:27 +0800 Subject: [PATCH 13/13] =?UTF-8?q?=E9=80=9A=E8=BF=87=E5=BC=80=E6=94=BE?= =?UTF-8?q?=E6=9D=83=E9=99=90=E8=AE=A1=E7=AE=97=E8=80=83=E8=AF=95=E7=BB=83?= =?UTF-8?q?=E4=B9=A0=E7=9A=84=E5=8F=82=E4=B8=8E=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/zgn/fazhi/mapper/UserInfoMapper.java | 16 ++++ .../com/zgn/fazhi/pojo/vo/ExaGradesDate.java | 20 ++++- .../zgn/fazhi/service/UserInfoService.java | 28 +++++++ .../impl/UserExaminationServiceImpl.java | 78 ++++++++++++++----- .../service/impl/UserInfoServiceImpl.java | 30 ++++++- 5 files changed, 148 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java b/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java index fe421c6..ef801ab 100644 --- a/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java +++ b/src/main/java/com/zgn/fazhi/mapper/UserInfoMapper.java @@ -60,4 +60,20 @@ public interface UserInfoMapper extends BaseMapper{ "WHERE username = #{username}") String getQuestion(@Param(value = "username") String username); + /** + * 动态条件查询用户id + * @param schoolId 学校id + * @param gradeId 年级id + * @param classId 班级id + * @return 用户id + */ + @Select("SELECT id FROM user_info " + + "WHERE 1=1 " + + "AND IF(#{schoolId} IS NULL, 1 = 1, school_id = #{schoolId}) " + + "AND IF(#{gradeId} IS NULL, 1 = 1, grade_id = #{gradeId}) " + + "AND IF(#{classId} IS NULL, 1 = 1, class_id = #{classId})") + List getIdListDynamic(@Param("schoolId") Integer schoolId, + @Param("gradeId") Integer gradeId, + @Param("classId") Integer classId); + } diff --git a/src/main/java/com/zgn/fazhi/pojo/vo/ExaGradesDate.java b/src/main/java/com/zgn/fazhi/pojo/vo/ExaGradesDate.java index f365b35..56c2b43 100644 --- a/src/main/java/com/zgn/fazhi/pojo/vo/ExaGradesDate.java +++ b/src/main/java/com/zgn/fazhi/pojo/vo/ExaGradesDate.java @@ -15,16 +15,34 @@ public class ExaGradesDate implements Serializable { private static final long serialVersionUID = 1L; + /** + * 平均分 + */ private Double avg; + /** + * 参加总人数 + */ private Integer numOfPeople; - private Double participationRate; + /** + * 参与率 + */ + private Integer participationRate; + /** + * 最高分 + */ private Integer maxScore; + /** + * 最低分 + */ private Integer minScore; + /** + * 及格率 + */ private String passRate; } diff --git a/src/main/java/com/zgn/fazhi/service/UserInfoService.java b/src/main/java/com/zgn/fazhi/service/UserInfoService.java index d7903d7..7482079 100644 --- a/src/main/java/com/zgn/fazhi/service/UserInfoService.java +++ b/src/main/java/com/zgn/fazhi/service/UserInfoService.java @@ -103,4 +103,32 @@ public interface UserInfoService extends IService { */ String getQuestion(String username); + /** + * 查询所在该学校的所有用户id + * @param schoolId 学校id + * @return 用户id + */ + List getIdListBySchoolId(Integer schoolId); + + /** + * 通过学校id和年级id查看该学校的该年级的全部用户id + * @param schoolId 学校id + * @param gradeId 年级id + * @return 用户id + */ + List getIdListByGradeId(Integer schoolId, Integer gradeId); + + /** + * 通过班级id查询该班级的所有用户 + * @param classId 班级id + * @return 用户id + */ + List getIdListByClassId(Integer classId); + + /** + * 计算当前用户量 + * @return 用户数 + */ + Integer countUser(); + } diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserExaminationServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserExaminationServiceImpl.java index d44f583..c5cf4c4 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserExaminationServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserExaminationServiceImpl.java @@ -5,14 +5,13 @@ import com.zgn.fazhi.controller.AppointmentController; import com.zgn.fazhi.exception.RestException; import com.zgn.fazhi.pojo.po.*; import com.zgn.fazhi.mapper.UserExaminationMapper; -import com.zgn.fazhi.pojo.vo.Answer; -import com.zgn.fazhi.pojo.vo.ExaGradesDate; -import com.zgn.fazhi.pojo.vo.SubmitExamination; +import com.zgn.fazhi.pojo.vo.*; import com.zgn.fazhi.service.*; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zgn.fazhi.utils.BelongCalendar; import com.zgn.fazhi.utils.ExaminationUtils; import com.zgn.fazhi.utils.RedisUtil; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -26,17 +25,16 @@ import java.util.*; /** *

- * 服务实现类 + * 服务实现类 *

* * @author wt * @since 2021-06-25 */ @Service +@Slf4j public class UserExaminationServiceImpl extends ServiceImpl implements UserExaminationService { - private static final Logger LOGGER = LoggerFactory.getLogger(UserExaminationServiceImpl.class); - @Autowired private UserExaminationMapper userExaminationMapper; @@ -44,6 +42,12 @@ public class UserExaminationServiceImpl extends ServiceImpl findAllByUid(Integer uid, Integer recordId) { return userExaminationMapper.selectList( @@ -53,7 +57,6 @@ public class UserExaminationServiceImpl extends ServiceImpl userExaminationQueryWrapper = new QueryWrapper<>(); @@ -62,7 +65,7 @@ public class UserExaminationServiceImpl extends ServiceImpl getScoreByUid(Integer uid, Integer recordId) { List allByUid = findAllByUid(uid, recordId); ArrayList scores = new ArrayList<>(); - if (allByUid.isEmpty()){ + if (allByUid.isEmpty()) { return null; } for (UserExamination userExamination : allByUid) { - if (!StringUtils.isEmpty(userExamination.getAchievement1())){ + if (!StringUtils.isEmpty(userExamination.getAchievement1())) { scores.add(userExamination.getAchievement1()); } else { - LOGGER.error("当前考试成绩为空uid:" + uid + ",rid: " + recordId); + log.error("当前考试成绩为空uid:" + uid + ",rid: " + recordId); } } return scores; @@ -92,9 +95,9 @@ public class UserExaminationServiceImpl extends ServiceImpl userExaminations = userExaminationMapper.selectList( - new QueryWrapper() - .eq("record_id", rid)); - if (userExaminations.isEmpty()){ + new QueryWrapper() + .eq("record_id", rid)); + if (userExaminations.isEmpty()) { throw new RestException(400, "该次考试练习无数据"); } // 获取最高分、最低分 @@ -103,18 +106,55 @@ public class UserExaminationServiceImpl extends ServiceImpl userExamination.getAchievement1() >= 60).count(); - DecimalFormat df=new DecimalFormat("0.00"); + Integer count = (int) userExaminations.stream().filter(userExamination -> userExamination.getAchievement1() >= 60).count(); + DecimalFormat df = new DecimalFormat("0.00"); String passRate = df.format((count / userExaminations.size())); - // 参与率需要查询本次考试的开放人群数量 + // 计算参与人数 + Integer total = takePartCount(rid); + // 计算参与率 + int takePartCount = userExaminations.size(); + int i = takePartCount * 100 / total; + log.info("参与率 : {}", i); ExaGradesDate exaGradesDate = new ExaGradesDate(); exaGradesDate.setAvg(avgScore) .setMaxScore(max) .setMinScore(min) - .setNumOfPeople(userExaminations.size()) + .setNumOfPeople(takePartCount) .setPassRate(passRate) - .setParticipationRate(null); + .setParticipationRate(i); return exaGradesDate; } + + private Integer takePartCount(Integer rid) { + if (examinationRecordService.getById(rid).getIfPublic() == 1) { + // 如果是公开,直接返回当前全部用户数量 + return userInfoService.countUser(); + } + ExaPermissionVoList exaPermissionByRid = examinationPermissionService.getExaPermissionByRid(rid); + List schoolList = exaPermissionByRid.getSchoolList(); + List gradeList = exaPermissionByRid.getGradeList(); + List classList = exaPermissionByRid.getClassList(); + List idList = new ArrayList<>(); + if (!StringUtils.isEmpty(schoolList)) { + for (ExaPermissionVo exaPermissionVo : schoolList) { + // 查询所有学校id,查找是该学校的所有人的id + idList.addAll(userInfoService.getIdListBySchoolId(exaPermissionVo.getSchoolId())); + } + } + if (!StringUtils.isEmpty(gradeList)) { + for (ExaPermissionVo exaPermissionVo : schoolList) { + // 查询该学校和该年级 + idList.addAll(userInfoService.getIdListByGradeId(exaPermissionVo.getSchoolId(), exaPermissionVo.getGradeId())); + } + } + if (!StringUtils.isEmpty(classList)) { + for (ExaPermissionVo exaPermissionVo : schoolList) { + // 查询班级 + idList.addAll(userInfoService.getIdListByClassId(exaPermissionVo.getClassId())); + } + } + // 去重计数返回 + return (int) idList.stream().distinct().count(); + } } diff --git a/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java b/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java index 3216ced..bae86e0 100644 --- a/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java +++ b/src/main/java/com/zgn/fazhi/service/impl/UserInfoServiceImpl.java @@ -31,6 +31,7 @@ import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; /** *

@@ -74,7 +75,7 @@ public class UserInfoServiceImpl extends ServiceImpl i // 没有用户名邮箱、手机号唯一标识,需要手动生成用户名返回给用户 String password = user.getPassword(); String username = user.getUsername(); - if (StringUtils.isEmpty(username)){ + if (StringUtils.isEmpty(username)) { // 如果username为空则生成六位数作为用户名 do { username = stringUtils.getRandomUsername(); @@ -286,7 +287,8 @@ public class UserInfoServiceImpl extends ServiceImpl i try { // 先查询缓存,缓存没有则查询数据库返回 if (redisUtil.hasKey(KEY + uid)) { - UserInfo userInfo = FastJsonUtils.toBean(redisUtil.get(KEY + uid), UserInfo.class);; + UserInfo userInfo = FastJsonUtils.toBean(redisUtil.get(KEY + uid), UserInfo.class); + ; return userInfo; } else { return selectPutCache(uid); @@ -308,7 +310,7 @@ public class UserInfoServiceImpl extends ServiceImpl i @Override public String retrieve(String answer, String username) { Integer uid = userMapper.retrieve(answer, username); - if (StringUtils.isEmpty(uid)){ + if (StringUtils.isEmpty(uid)) { throw new RestException(400, "验证信息错误"); } // 生成密钥保存redis 并返回 @@ -321,7 +323,7 @@ public class UserInfoServiceImpl extends ServiceImpl i @Override public Boolean updatePasswordByKey(String key, String password) { Object o = redisUtil.get(key); - if (StringUtils.isEmpty(o)){ + if (StringUtils.isEmpty(o)) { throw new RestException(400, "密钥无效"); } int uid = Integer.parseInt(o.toString()); @@ -333,4 +335,24 @@ public class UserInfoServiceImpl extends ServiceImpl i public String getQuestion(String username) { return userMapper.getQuestion(username); } + + @Override + public List getIdListBySchoolId(Integer schoolId) { + return userMapper.getIdListDynamic(schoolId, null, null); + } + + @Override + public List getIdListByGradeId(Integer schoolId, Integer gradeId) { + return userMapper.getIdListDynamic(schoolId, gradeId, null); + } + + @Override + public List getIdListByClassId(Integer classId) { + return userMapper.getIdListDynamic(null, null, classId); + } + + @Override + public Integer countUser() { + return userMapper.selectCount(null); + } } -- Gitee