2021-11-05 07:21:57 +00:00
|
|
|
package devicemngmt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
2021-11-05 08:40:07 +00:00
|
|
|
"fmt"
|
2021-11-05 07:21:57 +00:00
|
|
|
|
|
|
|
"github.com/Selly-Modules/logger"
|
|
|
|
"github.com/Selly-Modules/mongodb"
|
|
|
|
)
|
|
|
|
|
2021-11-05 08:40:07 +00:00
|
|
|
// CreateOptions ...
|
|
|
|
type CreateOptions struct {
|
2021-11-05 07:21:57 +00:00
|
|
|
DeviceID string
|
|
|
|
UserID string
|
|
|
|
UserAgent string
|
|
|
|
AppVersion string
|
|
|
|
IP string
|
|
|
|
FCMToken string
|
2021-11-05 08:40:07 +00:00
|
|
|
AuthToken string
|
2021-11-05 07:21:57 +00:00
|
|
|
Language string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create ...
|
2021-11-05 08:40:07 +00:00
|
|
|
func (s Service) Create(payload CreateOptions) error {
|
2021-11-05 07:21:57 +00:00
|
|
|
var (
|
|
|
|
col = s.getDeviceCollection()
|
|
|
|
ctx = context.Background()
|
|
|
|
)
|
|
|
|
|
2021-11-05 08:40:07 +00:00
|
|
|
// Validate payload
|
|
|
|
err := payload.validate()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-11-05 07:21:57 +00:00
|
|
|
// New device data from payload
|
|
|
|
deviceData, err := payload.newDevice()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-11-05 09:10:12 +00:00
|
|
|
// Find deviceID existed or not
|
|
|
|
if s.isDeviceIDExisted(ctx, deviceData.DeviceID) {
|
2021-11-05 08:40:07 +00:00
|
|
|
return errors.New("this device is already existed")
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create device
|
|
|
|
_, err = col.InsertOne(ctx, deviceData)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("devicemngt - Create ", logger.LogData{
|
|
|
|
"doc": deviceData,
|
|
|
|
"err": err.Error(),
|
|
|
|
})
|
2021-11-05 08:40:07 +00:00
|
|
|
return fmt.Errorf("error when create device: %s", err.Error())
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-11-05 08:40:07 +00:00
|
|
|
func (payload CreateOptions) newDevice() (result Device, err error) {
|
2021-11-05 07:21:57 +00:00
|
|
|
timeNow := now()
|
|
|
|
device := Device{
|
2021-11-05 09:24:53 +00:00
|
|
|
ID: mongodb.NewObjectID(),
|
|
|
|
DeviceID: payload.DeviceID,
|
|
|
|
OSName: getOSName(payload.UserAgent),
|
|
|
|
OSVersion: getOSVersion(payload.UserAgent),
|
|
|
|
IP: payload.IP,
|
|
|
|
Language: getLanguage(payload.Language),
|
|
|
|
AuthToken: payload.AuthToken,
|
|
|
|
LastActivatedAt: timeNow,
|
|
|
|
CreatedAt: timeNow,
|
|
|
|
FCMToken: payload.FCMToken,
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// App version
|
|
|
|
if payload.AppVersion != "" {
|
|
|
|
device.AppVersion = payload.AppVersion
|
|
|
|
device.IsMobile = true
|
|
|
|
}
|
|
|
|
|
|
|
|
result = device
|
|
|
|
return
|
|
|
|
}
|