golang-im聊天
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

90 rindas
2.1 KiB

  1. package device
  2. import (
  3. "context"
  4. "gim/pkg/logger"
  5. "gim/pkg/pb"
  6. "gim/pkg/rpc"
  7. "time"
  8. "go.uber.org/zap"
  9. )
  10. type deviceService struct{}
  11. var DeviceService = new(deviceService)
  12. // Register 注册设备
  13. func (*deviceService) Register(ctx context.Context, device *Device) error {
  14. err := DeviceDao.Save(device)
  15. if err != nil {
  16. return err
  17. }
  18. return nil
  19. }
  20. // SignIn 长连接登录
  21. func (*deviceService) SignIn(ctx context.Context, userId, deviceId int64, token string, connAddr string, clientAddr string) error {
  22. _, err := rpc.GetBusinessIntClient().Auth(ctx, &pb.AuthReq{UserId: userId, DeviceId: deviceId, Token: token})
  23. if err != nil {
  24. return err
  25. }
  26. // 标记用户在设备上登录
  27. device, err := DeviceRepo.Get(deviceId)
  28. if err != nil {
  29. return err
  30. }
  31. if device == nil {
  32. return nil
  33. }
  34. device.Online(userId, connAddr, clientAddr)
  35. err = DeviceRepo.Save(device)
  36. if err != nil {
  37. return err
  38. }
  39. return nil
  40. }
  41. // Auth 权限验证
  42. func (*deviceService) Auth(ctx context.Context, userId, deviceId int64, token string) error {
  43. _, err := rpc.GetBusinessIntClient().Auth(ctx, &pb.AuthReq{UserId: userId, DeviceId: deviceId, Token: token})
  44. if err != nil {
  45. return err
  46. }
  47. return nil
  48. }
  49. func (*deviceService) ListOnlineByUserId(ctx context.Context, userId int64) ([]*pb.Device, error) {
  50. devices, err := DeviceRepo.ListOnlineByUserId(userId)
  51. if err != nil {
  52. return nil, err
  53. }
  54. pbDevices := make([]*pb.Device, len(devices))
  55. for i := range devices {
  56. pbDevices[i] = devices[i].ToProto()
  57. }
  58. return pbDevices, nil
  59. }
  60. // ServerStop connect服务停止,需要将连接在这台connect上的设备标记为下线
  61. func (*deviceService) ServerStop(ctx context.Context, connAddr string) error {
  62. devices, err := DeviceRepo.ListOnlineByConnAddr(connAddr)
  63. if err != nil {
  64. return err
  65. }
  66. for i := range devices {
  67. // 因为是异步修改设备转台,要避免设备重连,导致状态不一致
  68. err = DeviceRepo.UpdateStatusOffline(devices[i])
  69. if err != nil {
  70. logger.Logger.Error("DeviceRepo.Save error", zap.Any("device", devices[i]), zap.Error(err))
  71. }
  72. time.Sleep(2 * time.Millisecond)
  73. }
  74. return nil
  75. }