devicemngmt/action_update.go

90 lines
2.0 KiB
Go
Raw Normal View History

2021-11-08 01:52:10 +00:00
package devicemngmt
import (
"context"
2021-11-23 09:44:42 +00:00
"errors"
2021-11-08 01:52:10 +00:00
"fmt"
2022-10-11 07:33:56 +00:00
"git.selly.red/Selly-Modules/logger"
"git.selly.red/Selly-Modules/mongodb"
2021-11-08 01:52:10 +00:00
"go.mongodb.org/mongo-driver/bson"
)
// UpdateOptions ...
type UpdateOptions struct {
2021-11-26 10:37:15 +00:00
UserID string
2021-11-08 01:52:10 +00:00
UserAgent string
AppVersion string
IP string
FCMToken string
AuthToken string
Language string
Model string
Manufacturer string
2021-12-10 04:46:25 +00:00
OsName string
OsVersion string
IsMobile bool
2021-11-08 01:52:10 +00:00
}
// UpdateByDeviceID ...
func (s Service) UpdateByDeviceID(deviceID string, payload UpdateOptions) error {
var (
ctx = context.Background()
col = s.getDeviceCollection()
cond = bson.M{
2021-11-08 10:23:03 +00:00
"deviceId": deviceID,
2021-11-08 01:52:10 +00:00
}
)
2021-11-23 09:44:42 +00:00
total, _ := col.CountDocuments(ctx, cond)
if total == 0 {
return errors.New("deviceId not found")
}
2021-11-08 01:52:10 +00:00
// Validate payload
err := payload.validate()
if err != nil {
return err
}
2021-11-08 02:46:17 +00:00
// Get userAgent data
osName, osVersion, isMobile := getUserAgentData(payload.UserAgent)
2021-12-10 04:46:25 +00:00
if osName == "" || osVersion == "" {
osName = payload.OsName
osVersion = payload.OsVersion
isMobile = payload.IsMobile
}
2021-11-08 02:46:17 +00:00
2021-11-08 01:52:10 +00:00
// Setup update data
2021-11-26 10:37:15 +00:00
userID, _ := mongodb.NewIDFromString(payload.UserID)
2021-11-08 01:52:10 +00:00
updateData := bson.M{
"$set": bson.M{
2021-11-26 10:37:15 +00:00
"userId": userID,
2021-11-08 02:46:17 +00:00
"osName": osName,
"osVersion": osVersion,
2021-11-08 01:52:10 +00:00
"ip": payload.IP,
"language": getLanguage(payload.Language),
"authToken": payload.AuthToken,
"fcmToken": payload.FCMToken,
"model": payload.Model,
"manufacturer": payload.Manufacturer,
"appVersion": payload.AppVersion,
2021-11-08 02:46:17 +00:00
"isMobile": isMobile,
2021-11-08 01:52:10 +00:00
"lastActivatedAt": now(),
},
}
// Update
_, err = col.UpdateOne(ctx, cond, updateData)
if err != nil {
2021-11-10 10:08:39 +00:00
logger.Error("devicemngmt - updateByDeviceID", logger.LogData{
2022-10-05 10:23:29 +00:00
Source: "devicemngmt.UpdateByDeviceID",
Message: err.Error(),
Data: deviceID,
2021-11-08 01:52:10 +00:00
})
return fmt.Errorf("error when update device: %s", err.Error())
}
return nil
}