From 8a7b4bb9194e9185800793c4447bf4cab99cd6fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pavel=20=C5=A0koda?= Date: Tue, 1 Sep 2020 10:16:21 +0200 Subject: [PATCH] Improve user agent --- pkg/pmapi/useragent.go | 19 +++++++++++++++++-- pkg/pmapi/useragent_test.go | 5 +++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/pkg/pmapi/useragent.go b/pkg/pmapi/useragent.go index 6c8f452f..1b24aa5b 100644 --- a/pkg/pmapi/useragent.go +++ b/pkg/pmapi/useragent.go @@ -20,18 +20,33 @@ package pmapi import ( "fmt" "runtime" + "strings" ) +// removeBrackets handle unwanted brackets in client identification string and join with given joinBy parameter +// Mac OS X Mail/13.0 (3601.0.4) -> Mac OS X Mail/13.0-3601.0.4 (joinBy = "-") +func removeBrackets(s string, joinBy string) (r string) { + r = strings.ReplaceAll(s, " (", joinBy) + r = strings.ReplaceAll(r, "(", joinBy) // Should be faster than regex. + r = strings.ReplaceAll(r, ")", "") + + return +} + func formatUserAgent(clientName, clientVersion, os string) string { client := "" if clientName != "" { - client = clientName + client = removeBrackets(clientName, "-") if clientVersion != "" { - client += "/" + clientVersion + client += "/" + removeBrackets(clientVersion, "-") } } + if os == "" { os = runtime.GOOS } + + os = removeBrackets(os, " ") + return fmt.Sprintf("%s (%s)", client, os) } diff --git a/pkg/pmapi/useragent_test.go b/pkg/pmapi/useragent_test.go index 0ccf596b..842c8411 100644 --- a/pkg/pmapi/useragent_test.go +++ b/pkg/pmapi/useragent_test.go @@ -48,3 +48,8 @@ func TestUpdateCurrentUserAgentClientNameAndVersion(t *testing.T) { userAgent := formatUserAgent("mail", "ver", "os") assert.Equal(t, "mail/ver (os)", userAgent) } + +func TestRemoveBrackets(t *testing.T) { + userAgent := formatUserAgent("mail (submail)", "ver (subver)", "os (subos)") + assert.Equal(t, "mail-submail/ver-subver (os subos)", userAgent) +}