Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Reuse cast UA detector

Neeraj Gupta3b94c80fde7b
diff --git a/server/pkg/utils/ua/ua.go b/server/pkg/utils/ua/ua.go
index b18530d030..6232d89f95 100644
--- a/server/pkg/utils/ua/ua.go
+++ b/server/pkg/utils/ua/ua.go
@@ -2,23 +2,37 @@ package ua
import (
"errors"
+ "sync"
"github.com/slipros/devicedetector"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
+var (
+ errFailedToParseUserAgent = errors.New("failed to parse user agent")
+
+ detectorOnce sync.Once
+ detectorMu sync.Mutex
+ detector *devicedetector.DeviceDetector
+ detectorErr error
+)
+
// Returns the type of device based on the user agent.
// Example: Desktop, Mobile, Tablet, TV, etc.
// Returns empty string if the user agent is invalid or the device type is not found, or err is not nil.
-func GetDeviceType(ua string) (string, error) {
- dd, dderr := devicedetector.NewDeviceDetector()
- if dderr != nil {
- return "", dderr
+func GetDeviceType(userAgent string) (string, error) {
+ dd, err := getDetector()
+ if err != nil {
+ return "", err
}
- info := dd.Parse(ua)
+
+ detectorMu.Lock()
+ info := dd.Parse(userAgent)
+ detectorMu.Unlock()
+
if info == nil {
- return "", errors.New("failed to parse user agent")
+ return "", errFailedToParseUserAgent
}
if info.Type == "" {
return "", nil
@@ -26,3 +40,10 @@ func GetDeviceType(ua string) (string, error) {
titleCaser := cases.Title(language.English)
return titleCaser.String(info.Type), nil
}
+
+func getDetector() (*devicedetector.DeviceDetector, error) {
+ detectorOnce.Do(func() {
+ detector, detectorErr = devicedetector.NewDeviceDetector()
+ })
+ return detector, detectorErr
+}
diff --git a/server/pkg/utils/ua/ua_test.go b/server/pkg/utils/ua/ua_test.go
index dd7756ba4c..630e889511 100644
--- a/server/pkg/utils/ua/ua_test.go
+++ b/server/pkg/utils/ua/ua_test.go
@@ -1,6 +1,9 @@
package ua
-import "testing"
+import (
+ "sync"
+ "testing"
+)
func TestGetDeviceType(t *testing.T) {
deviceType, err := GetDeviceType("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1")
@@ -21,3 +24,31 @@ func TestGetDeviceTypeReturnsErrorForUnparsableUserAgent(t *testing.T) {
t.Fatalf("GetDeviceType = %q, want empty string", deviceType)
}
}
+
+func TestGetDeviceTypeConcurrent(t *testing.T) {
+ const userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
+ const workers = 16
+
+ var wg sync.WaitGroup
+ errs := make(chan string, workers)
+ for i := 0; i < workers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ deviceType, err := GetDeviceType(userAgent)
+ if err != nil {
+ errs <- err.Error()
+ return
+ }
+ if deviceType != "Smartphone" {
+ errs <- "unexpected device type"
+ }
+ }()
+ }
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ t.Fatal(err)
+ }
+}