1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

fix: support user agents set by browser plugin (see #237)

This commit is contained in:
Ferdinand Mütsch 2023-03-16 21:02:28 +01:00
parent c9f2518fbc
commit bfeebafb2f
4 changed files with 969 additions and 815 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
package api
import (
"github.com/duke-git/lancet/v2/condition"
"github.com/go-chi/chi/v5"
"github.com/muety/wakapi/helpers"
"net/http"
@ -87,11 +88,22 @@ func (h *HeartbeatApiHandler) Post(w http.ResponseWriter, r *http.Request) {
return
}
hb.OperatingSystem = opSys
hb.Editor = editor
hb.Machine = machineName
// TODO: unit test this
if hb.UserAgent != "" {
userAgent = hb.UserAgent
localOpSys, localEditor, _ := utils.ParseUserAgent(userAgent)
opSys = condition.TernaryOperator[bool, string](localOpSys != "", localOpSys, opSys)
editor = condition.TernaryOperator[bool, string](localEditor != "", localEditor, editor)
}
if hb.Machine != "" {
machineName = hb.Machine
}
hb.User = user
hb.UserID = user.ID
hb.Machine = machineName
hb.OperatingSystem = opSys
hb.Editor = editor
hb.UserAgent = userAgent
if !hb.Valid() || !hb.Timely(h.config.App.HeartbeatsMaxAge()) {

View File

@ -49,6 +49,12 @@ func TestCommon_ParseUserAgent(t *testing.T) {
"emacs",
nil,
},
{
"Chrome/111.0.0.0 chrome-wakatime/3.0.6",
"",
"chrome",
nil,
},
}
for _, test := range tests {

View File

@ -78,7 +78,7 @@ func ParsePageParamsWithDefault(r *http.Request, page, size int) *PageParams {
}
func ParseUserAgent(ua string) (string, string, error) {
re := regexp.MustCompile(`(?iU)^wakatime\/(?:v?[\d+.]+|unset)\s\((\w+)-.*\)\s.+\s([^\/\s]+)-wakatime\/.+$`)
re := regexp.MustCompile(`(?iU)^(?:(?:wakatime|chrome|firefox)\/(?:v?[\d+.]+|unset)\s)?(?:\((\w+)-.*\)\s.+\s)?([^\/\s]+)-wakatime\/.+$`)
groups := re.FindAllStringSubmatch(ua, -1)
if len(groups) == 0 || len(groups[0]) != 3 {
return "", "", errors.New("failed to parse user agent string")