github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/client/auth/device.go (about) 1 package auth 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 "strconv" 8 9 "github.com/LagrangeDev/LagrangeGo/utils/crypto" 10 "github.com/LagrangeDev/LagrangeGo/utils/platform" 11 12 "github.com/LagrangeDev/LagrangeGo/utils" 13 ) 14 15 type DeviceInfo struct { 16 Guid string `json:"guid"` 17 DeviceName string `json:"device_name"` 18 SystemKernel string `json:"system_kernel"` 19 KernelVersion string `json:"kernel_version"` 20 } 21 22 func NewDeviceInfo(uin int) *DeviceInfo { 23 return &DeviceInfo{ 24 Guid: fmt.Sprintf("%X", crypto.MD5Digest(utils.S2B(strconv.Itoa(uin)))), 25 DeviceName: fmt.Sprintf("Lagrange-%X", crypto.MD5Digest(utils.S2B(strconv.Itoa(uin)))[0:4]), 26 SystemKernel: fmt.Sprintf("%s %s", platform.System(), platform.Version()), 27 KernelVersion: platform.Version(), 28 } 29 } 30 31 func LoadOrSaveDevice(path string) (*DeviceInfo, error) { 32 data, err := os.ReadFile(path) 33 if err != nil { 34 deviceinfo := NewDeviceInfo(int(crypto.RandU32())) 35 return deviceinfo, deviceinfo.Save(path) 36 } 37 var dinfo DeviceInfo 38 err = json.Unmarshal(data, &dinfo) 39 if err != nil { 40 deviceinfo := NewDeviceInfo(int(crypto.RandU32())) 41 return deviceinfo, deviceinfo.Save(path) 42 } 43 return &dinfo, nil 44 } 45 46 func (deviceInfo *DeviceInfo) Save(path string) error { 47 data, err := json.Marshal(deviceInfo) 48 if err != nil { 49 return err 50 } 51 err = os.WriteFile(path, data, 0666) 52 if err != nil { 53 return err 54 } 55 return nil 56 }