Skip to content

Commit

Permalink
Merge pull request #10 from Morgan66666/master
Browse files Browse the repository at this point in the history
aa
  • Loading branch information
MuuuShin authored Dec 11, 2023
2 parents 0903c0d + bf537dd commit ac8d6dd
Show file tree
Hide file tree
Showing 21 changed files with 361 additions and 124 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cse.ooad.project.service.websocket;
package cse.ooad.project.config;

import cse.ooad.project.service.websocket.HttpAuthHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
Expand All @@ -13,14 +14,13 @@ public class WebsocketConfig implements WebSocketConfigurer {
@Autowired
private HttpAuthHandler httpAuthHandler;
@Autowired
private Interceptor Interceptor;
private cse.ooad.project.service.websocket.Interceptor Interceptor;

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry
.addHandler(httpAuthHandler, "messagePush")
.addHandler(httpAuthHandler, "ws/create")
.addInterceptors(Interceptor)
.setAllowedOrigins("*");
}

}
10 changes: 7 additions & 3 deletions src/main/java/cse/ooad/project/controller/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
import cse.ooad.project.service.LoginService;
import cse.ooad.project.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
Expand All @@ -22,7 +24,7 @@ public class AuthController {
private LoginService loginService;

@PostMapping("/login")
public Result<String> login(@RequestBody Map<String, Object> jsonMap) {
public Result<List<Object>> login(@RequestBody Map<String, Object> jsonMap) {
String username = (String) jsonMap.get("username");
String password = (String) jsonMap.get("password");
String isTeacherStr = (String) jsonMap.get("isTeacher");
Expand All @@ -40,7 +42,8 @@ public Result<String> login(@RequestBody Map<String, Object> jsonMap) {
claims.put("isTeacher", true);
String jwt = JwtUtils.generateToken(claims);
log.info(result.getTeacherId() + "Login successfully");
return Result.success("success", jwt);
List<Object> list = List.of(jwt, result);
return Result.success("success", list);
} else {
Student result = loginService.loginStudent(username, password);
if (result == null) {
Expand All @@ -53,7 +56,8 @@ public Result<String> login(@RequestBody Map<String, Object> jsonMap) {
claims.put("isTeacher", false);
String jwt = JwtUtils.generateToken(claims);
log.info(result.getStudentId() + "Login successfully");
return Result.success("success", jwt);
List<Object> list = List.of(jwt, result);
return Result.success("success", list);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ public class AuthInterceptor implements HandlerInterceptor {

@Scheduled(fixedRate = 60 * 60 * 1000)
public void clearBlackList() {
blackList.clear();
for (String jwt : blackList) {
try {
JwtUtils.parseJWT(jwt);
} catch (Exception e) {
blackList.remove(jwt);
}
}
}

@Override
Expand Down
64 changes: 58 additions & 6 deletions src/main/java/cse/ooad/project/controller/TeamController.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.springframework.data.relational.core.sql.In;
import org.springframework.web.bind.annotation.*;

import java.sql.Time;
import java.util.List;
import java.util.Map;

Expand All @@ -39,7 +40,7 @@ public class TeamController {


@PostMapping("/trans-room")
public Result<String> transRoom(@RequestBody Map<String, Object> JsonData){
public Result<String> transRoom(@RequestBody Map<String, Object> JsonData) {
String studentId1 = (String) JsonData.get("studentId1");
String studentId2 = (String) JsonData.get("studentId2");
boolean success = teacherService.transRoom(Long.parseLong(studentId1), Long.parseLong(studentId2));
Expand Down Expand Up @@ -128,15 +129,20 @@ public Result<String> leaveTeam(@PathVariable("teamId") String teamId, @RequestH
}


@PostMapping("/{teamId}/join")
public Result<String> joinTeam(@PathVariable("teamId") String teamId, @RequestHeader("Authorization") String token) {
@PostMapping("/join")
public Result<String> joinTeam(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> JsonData) {
String leaderId = (String) JsonData.get("leaderId");
String message = (String) JsonData.get("message");

Claims claims;
try {
claims = JwtUtils.parseJWT(token);
} catch (Exception e) {
return Result.error("fail");
}
boolean success = studentService.joinGroup(Long.parseLong(claims.get("id").toString()), Long.parseLong(teamId));
// boolean success = studentService.joinGroup(Long.parseLong(claims.get("id").toString()), Long.parseLong(teamId));

boolean success = studentService.sendApply(Long.parseLong(claims.get("id").toString()), Long.parseLong(leaderId), message);
if (success) {
return Result.success("success", null);
} else {
Expand Down Expand Up @@ -230,7 +236,6 @@ public Result<Group> getTeamInfo(@PathVariable("teamId") String teamId) {
}



@GetMapping("")
public Result<List<Group>> getAllTeamInfo(@RequestBody Map<String, Object> JsonData, @RequestHeader("Authorization") String token) {
Integer offset = (Integer) JsonData.get("offset");
Expand Down Expand Up @@ -262,14 +267,61 @@ public Result<String> createTeam(@RequestBody Map<String, Object> JsonData, @Req
return Result.error("fail");
}

Group group = studentService.createGroup(Long.parseLong(claims.get("id").toString()), teamName);
Group group = studentService.createGroup(Long.parseLong(claims.get("id").toString()), teamName);
if (group != null) {
return Result.success("success", null);
} else {
return Result.error("fail");
}
}

@GetMapping("/teams/finduser/{sleeptime}/{awaketime}/{query}")
public Result<List<Group>> findUser(@PathVariable("sleeptime") String sleeptime, @PathVariable("awaketime") String awaketime, @PathVariable("query") String query, @RequestHeader("Authorization") String token) {
log.info("find team");
Time awakeTime = Time.valueOf(awaketime);
Time sleepTime = Time.valueOf(sleeptime);
Claims claims;
try {
claims = JwtUtils.parseJWT(token);
} catch (Exception e) {
return Result.error("not login");
}
String userId = claims.get("id").toString();
Student student = searchService.searchStudentById(Long.parseLong(userId));
Long gender = Long.parseLong(String.valueOf(student.getGender()));
Long type = Long.parseLong(String.valueOf(student.getType()));
List<Group> groups = searchService.searchGroups(gender, awakeTime, sleepTime, type, query);

if (groups != null) {
return Result.success("success", groups);
}

return Result.error("fail");


}


@PostMapping("/accept")
public Result<String> acceptTeam(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> JsonData) {
Claims claims;
try {
claims = JwtUtils.parseJWT(token);
} catch (Exception e) {
return Result.error("not login");
}
String userId = claims.get("id").toString();
String msgId = (String) JsonData.get("msgId");
String isAccepted = (String) JsonData.get("isAccepted");
boolean success = studentService.handleApply(Long.parseLong(msgId), isAccepted.equals("1"), Long.parseLong(userId));
// log.warn("hhhhhh");
if (success) {
return Result.success("success", null);
} else {
return Result.error("fail");
}
}




Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public interface BuildingRepository extends JpaRepository<Building, Long> {

List<Building> getBuildingsByRegionId(Long regionId);

Building getBuildingByBuildingId(Long buildingId);

Long removeByBuildingId(Long BuildingId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ public interface FloorRepository extends JpaRepository<Floor, Long> {

List<Floor> getFloorsByBuildingId(Long id);

Floor getFloorByName(String name);
Floor getFloorByFloorId(Long floorId);


Integer removeByFloorId(Long id);

List<Floor> findAllByBuildingIdIn(List<Long> buildingIds);


}
4 changes: 3 additions & 1 deletion src/main/java/cse/ooad/project/repository/MsgRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ public interface MsgRepository extends JpaRepository<Msg, Long> {

List<Msg> getMsgsBySrcIdAndDstId(Long srcId, Long DistId);

List<Msg> getMsgsByDstIdAndStatus(Long DistId, Integer status);
List<Msg> getMsgsByDstIdAndStatusAndType(Long DistId, Integer status, Integer type);


Msg getMsgByMsgId(Long msgId);

List<Msg> getMsgsByDstId(Long DistId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ public interface RegionRepository extends JpaRepository<Region, Long> {

Integer deleteByRegionId(Long id);

//Region getRegionByRegionId(Long id);
Region getRegionByRegionId(Long id);
}
6 changes: 6 additions & 0 deletions src/main/java/cse/ooad/project/repository/RoomRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ interface GroupStarListProjection {

List<GroupStarListProjection> getGroupStarListByRoomId(Long id);

List<Room> findAllByFloorIdIn(List<Long> floorIds);


@Query("SELECT r FROM Room r JOIN FETCH r.groupStarList WHERE r.floorId IN :ids")
List<Room> findAllWithGroupStarListByBuildingIds(@Param("ids") List<Long> ids);

// GroupStarListProjection1 getGroupByRoomId(Long id);

@Transactional
Expand Down
13 changes: 12 additions & 1 deletion src/main/java/cse/ooad/project/service/GroupService.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
import jakarta.transaction.Transactional;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class GroupService {

@Autowired
Expand Down Expand Up @@ -122,6 +124,7 @@ public boolean chooseRoom(Long groupId, Long roomId) {
Group group = groupRepository.getGroupByGroupId(groupId);
Room room = roomRepository.getRoomsByRoomId(roomId);
if (group == null|| room == null) {
log.info("group or room is null");
return false;
}
Student lead = studentRepository.getStudentByStudentId(group.getLeader());
Expand All @@ -130,22 +133,25 @@ public boolean chooseRoom(Long groupId, Long roomId) {
int stage = timelineService.getStage(lead.getType());
//判断房间类型对不对
if ((room.getType() - 1) / 4 + 1 != lead.getType()) {
log.info("room type is not right");
return false;
}
int roomCapacity = room.getType() % 4 == 0 ? 4 : room.getType() % 4;
if (stage == 2) {
//如果选房的人没有star
if (!group.getRoomStarList().contains(room)) {
log.info("group has no star");
return false;
}
//房间已经被选了
if (room.getStatus() != RoomStatus.UNSELECTED.statusCode) {

log.info("room has been selected");
return false;
}

//如果选房的人数不对
if (group.getMemberList().size() != roomCapacity) {
log.info("group member number is not right");
return false;
}
//选房
Expand All @@ -155,13 +161,15 @@ public boolean chooseRoom(Long groupId, Long roomId) {
room.setStatus(RoomStatus.SELECTED.statusCode);
roomRepository.save(room);
groupRepository.save(group);
log.info("choose room success");

}
if (stage == 3) {
Group roomMaster = groupRepository.getGroupByRoomId(room.getRoomId());
//看有人没人
if (roomMaster == null) {
if (group.getMemberList().size() > roomCapacity) {
log.info("group member number is not right");
return false;
}
group.setRoomId(roomId);
Expand All @@ -170,13 +178,16 @@ public boolean chooseRoom(Long groupId, Long roomId) {
room.setStatus(RoomStatus.SELECTED.statusCode);
roomRepository.save(room);
groupRepository.save(group);
log.info("choose room success");
return true;

} else {
if (roomMaster.getMemberList().size() + group.getMemberList().size()
> roomCapacity) {
log.info("group member number is not right");
return false;
}
log.info("combine groups");
return combineGroups(roomMaster.getGroupId(), group.getGroupId());
}

Expand Down
14 changes: 10 additions & 4 deletions src/main/java/cse/ooad/project/service/MsgService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import cse.ooad.project.service.websocket.WsSessionManager;
import cse.ooad.project.model.Student;
import cse.ooad.project.utils.MessageStatus;
import cse.ooad.project.utils.MessageType;
import java.sql.Timestamp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -41,6 +42,7 @@ public void sendSystemMsg(List<Student> students, String content){
msg.setSrcId(0L);
msg.setDstId(t.getStudentId());
msg.setBody(content);
msg.setType(MessageType.SYSTEM.typeCode);
msg.setStatus(MessageStatus.UNREAD.getStatusCode());
msg.setTimestamp(new Timestamp(System.currentTimeMillis()));
forwardMsg(msg);
Expand All @@ -49,14 +51,14 @@ public void sendSystemMsg(List<Student> students, String content){
}

public void forwardMsg(Msg msg) {
String session = WsSessionManager.USER_POOL.get(msg.getDstId());
try {
//在线就转发消息
if (session != null) {
WebSocketSession webSocketSession = WsSessionManager.get(session);
if (msg != null) {
WebSocketSession webSocketSession = WsSessionManager.get(msg.getDstId().toString());
if (webSocketSession != null) {
System.out.println("转发信息"+msg.getBody()+"给"+msg.getDstId());
webSocketSession.sendMessage(new TextMessage(gson.toJson(msg)));
msg.setStatus(MessageStatus.Read.getStatusCode());
msg.setStatus(MessageStatus.READ.getStatusCode());
}
}
} catch (Exception e) {
Expand All @@ -65,4 +67,8 @@ public void forwardMsg(Msg msg) {
}
msgRepository.save(msg);
}

public List<Msg> getMsgByDistId(Long distId) {
return msgRepository.getMsgsByDstId(distId);
}
}
Loading

0 comments on commit ac8d6dd

Please sign in to comment.