NeteaseMessageService.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package com.izouma.nineth.service.netease;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.izouma.nineth.domain.User;
  5. import com.izouma.nineth.domain.netease.NeteaseMessage;
  6. import com.izouma.nineth.dto.PageQuery;
  7. import com.izouma.nineth.exception.BusinessException;
  8. import com.izouma.nineth.repo.netease.NeteaseMessageRepo;
  9. import com.izouma.nineth.repo.UserRepo;
  10. import com.izouma.nineth.utils.JpaUtils;
  11. import lombok.AllArgsConstructor;
  12. import org.springframework.data.domain.Page;
  13. import org.springframework.stereotype.Service;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. @Service
  17. @AllArgsConstructor
  18. public class NeteaseMessageService {
  19. private NeteaseMessageRepo neteaseMessageRepo;
  20. private NeteaseUserService neteaseUserService;
  21. private UserRepo userRepo;
  22. public Page<NeteaseMessage> all(PageQuery pageQuery) {
  23. return neteaseMessageRepo
  24. .findAll(JpaUtils.toSpecification(pageQuery, NeteaseMessage.class), JpaUtils.toPageRequest(pageQuery));
  25. }
  26. public NeteaseMessage sendMessage(NeteaseMessage msg) {
  27. User from = userRepo.findById(Long.valueOf(msg.getFromId())).orElseThrow(new BusinessException("未找到用户"));
  28. // User to = userRepo.findById(Long.valueOf(msg.getToId())).orElseThrow(new BusinessException("未找到用户"));
  29. msg.setFromAvatar(from.getAvatar());
  30. msg.setFromNickName(from.getNickname());
  31. // msg.setToAvatar(to.getAvatar());
  32. // msg.setToNickName(to.getNickname());
  33. String url = "msg/sendMsg.action";
  34. String contentType = "application/x-www-form-urlencoded;charset=utf-8";
  35. Map<String, Object> params = new HashMap<>();
  36. params.put("from", msg.getFromId());
  37. params.put("to", msg.getToId());
  38. params.put("ope", msg.getOpe());
  39. params.put("type", msg.getType());
  40. params.put("body", msg.getBody());
  41. params.put("markRead", 1);
  42. String result = neteaseUserService.httpPost(url, contentType, params);
  43. JSONObject jsonObject = JSON.parseObject(result);
  44. Integer code = jsonObject.getInteger("code");
  45. if (code != 200) {
  46. throw new BusinessException("发信出错,请检查后重新发送");
  47. }
  48. JSONObject data = jsonObject.getJSONObject("data");
  49. msg.setMsgId(data.getLong("msgid"));
  50. msg.setTimetag(data.getLong("timetag"));
  51. return neteaseMessageRepo.save(msg);
  52. }
  53. }